How to get the class Type in a base class static method in .NET?
All I want to do is similar to:
public abstract class BaseClass
{
public static Type GetType()
{
return typeof(BaseClass);
}
}
But when I derive it
public class DerivedClass : BaseClass
{
}
I want to get
Assert.AreEqual(typeof(DerivedC开发者_StackOverflow中文版lass), DerivedClass.GetType());
How to change the BaseClass to make this assertion true?
Static methods are not inherited.
The compiler substitutes BaseClass
for DerivedClass
when calling a base class' static methods through one of its derived classes. For example, here's the IL code for a call to DerivedClass.GetType()
:
IL_0002: call class [mscorlib]System.Type Tests.Program/BaseClass::GetType()
You can't do this because your only route to a derived type from one of its bases is from an instance - and static methods don't take an instance.
I'm hoping that your example is for simplicity because otherwise re-implementing GetType() seems a bit pointless - since the object.GetType()
will do exactly what you want.
If you actually need to do this via a statically invoked method - you can't because no type information is actually available to a static method (as I say in the first paragraph).
If you actually invoking this method via an instance (but I must ask why!?) then you can do one of the following
a) Make your method an instance method on the base. It can then do this.GetType()
(using the .Net base method) and it'll return the ultimate subtype of the instance.
b) Define an extension method for BaseClass
that does something very similar:
public static Type GetType2(this BaseClass instance)
{
return instance.GetType();
}
精彩评论