如何在.NET的基类静态方法中获取类Type? [英] How to get the class Type in a base class static method in .NET?

查看:164
本文介绍了如何在.NET的基类静态方法中获取类Type?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的所有事情都类似于:

All I want to do is similar to:

public abstract class BaseClass
{
    public static Type GetType()
    {
        return typeof(BaseClass);
    }
}

但是当我得到它

public class DerivedClass : BaseClass
{
}

我想得到

Assert.AreEqual(typeof(DerivedClass), DerivedClass.GetType());

如何更改BaseClass以使此断言为真?

How to change the BaseClass to make this assertion true?

推荐答案

静态方法不会被继承.

当通过其派生类之一调用基类的静态方法时,编译器将BaseClass替换为DerivedClass.例如,这是调用DerivedClass.GetType()的IL代码:

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()

这篇关于如何在.NET的基类静态方法中获取类Type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆