More specific Type from base shared constructor
How do I get using reflection the most generic type from a shared constructor in the base class :
Public Class Foo()
Shared Sub New()
'Here we have code to get the type!
开发者_C百科 MethodBase.GetCurrentMethod().DeclaringType
End
End Class
Public Class Bar()
Inherits Foo
End Class
I expect the result to be Bar
type and not the Foo
. Is it possible?
First, it seems you want to find the most derived type (or the most specific type), not the most generic type -- which would mean rather the opposite (either, that generics are involved, or that the most general type is being sought).
While it may be possible to do this using reflection, your need for it might indicate that you have your class design wrong, or less than optimal.
First, constructors aren't virtual methods, so inside a constructor (IIRC), the Me
object reference is of the type that contains this constructor.
What you could do is reflect over all of an assembly's types and find all those that are derived from Foo
. You would then have to build a inheritance graph of these types and assign a number to each saying how far it is derived from Foo
(number of inheritance levels). You could then check the Me
object reference against all of the types you've identified (see if Me
can be cast to each of them), and from that subset, choose the one type with the largest number of inheritance levels.
I hope that from this, you'll see that it's probably not worth the effort. It would be more interesting, and probably more helpful, to re-think why you need to do this, and if possible, find a way to avoid it.
精彩评论