matthew.abercrombie
Member
- Joined
- May 28, 2010
- Messages
- 5
- Programming Experience
- 5-10
I have a situation where I need to make sure that a class implements a set of Shared methods. The context is quite complex, so I'll spare the details.
I basically have an abstract class that deals heavily with Generics. I need to call a Shared method on the Generic class T. I need to make sure the Shared method is implemented.
I could use reflection to check for the implementation and call the method if it exists or throw an exception otherwise. However, since the derived class is not "aware" that it needs to implement this method, I feel that the exception will get thrown more often than not.
Having the derived class also implement an Interface and force this via constraints placed on T in the abstract class would work great, except that the method has to be Shared, which rules out using an Interface. However, this type of logic should give you a good idea of what I'm trying to accomplish:
In conclusion, is there a way to enforce an "Interface-like contract" on a class without using an Interface, so that you can force a Shared method to be implemented?
I basically have an abstract class that deals heavily with Generics. I need to call a Shared method on the Generic class T. I need to make sure the Shared method is implemented.
I could use reflection to check for the implementation and call the method if it exists or throw an exception otherwise. However, since the derived class is not "aware" that it needs to implement this method, I feel that the exception will get thrown more often than not.
Having the derived class also implement an Interface and force this via constraints placed on T in the abstract class would work great, except that the method has to be Shared, which rules out using an Interface. However, this type of logic should give you a good idea of what I'm trying to accomplish:
VB.NET:
Public MustInherit Class MyAbstractClass(Of T As ISomeInterface)
...
T.Bar() 'THIS IS BETTER THAN REFLECTION
...
End Class
Public Interface ISomeInterface
Sub Bar() 'I NEED THIS TO BE SHARED
...
End Interface
Public Class Foo
Implements ISomeInterface
...
'THE FOLLOWING IS NOT POSSIBLE BECAUSE Interfaces DON'T DO Shared
Public Shared Sub Bar() Implements ISomeInterface.Bar
...
End Sub
End Class
Public Class MyDerivedClass
Inherits MyAbstractClass(Of Foo)
...
End Class
In conclusion, is there a way to enforce an "Interface-like contract" on a class without using an Interface, so that you can force a Shared method to be implemented?