【问题标题】:C# : how do you obtain a class' base class?C#:你如何获得一个类的基类?
【发布时间】:2010-11-09 11:13:08
【问题描述】:

在 C# 中,如何获得对给定类的基类的引用?

例如,假设你有一个特定的类MyClass,并且你想获得对MyClass'超类的引用。

我有这样的想法:

Type  superClass = MyClass.GetBase() ;
// then, do something with superClass

但是,似乎没有合适的GetBase 方法。

【问题讨论】:

    标签: c# superclass


    【解决方案1】:

    从当前类的类型中使用反射。

     Type superClass = myClass.GetType().BaseType;
    

    【讨论】:

      【解决方案2】:
      Type superClass = typeof(MyClass).BaseType;
      

      另外,如果不知道当前对象的类型,可以使用GetType获取类型,然后获取该类型的BaseType:

      Type baseClass = myObject.GetType().BaseType;
      

      documentation

      【讨论】:

        【解决方案3】:

        这将获取基本类型(如果存在)并创建它的实例:

        Type baseType = typeof(MyClass).BaseType;
        object o = null;
        if(baseType != null) {
            o = Activator.CreateInstance(baseType);
        }
        

        或者,如果您在编译时不知道类型,请使用以下内容:

        object myObject;
        Type baseType = myObject.GetType().BaseType;
        object o = null;
        if(baseType != null) {
            o = Activator.CreateInstance(baseType);
        }
        

        请参阅 MSDN 上的 Type.BaseTypeActivator.CreateInstance

        【讨论】:

          【解决方案4】:

          Type.BaseType 属性是您正在寻找的。​​p>

          Type  superClass = typeof(MyClass).BaseType;
          

          【讨论】:

            【解决方案5】:

            obj.base 将从派生对象 obj 的实例中获取对父对象的引用。

            typeof(obj).BaseType 将从派生对象 obj 的实例中获取对父对象类型的引用。

            【讨论】:

            • basethis 仅在实例方法中可用。
            【解决方案6】:

            如果你想检查一个类是否是另一个类的子类,你可以使用 is

            if (variable is superclass){ //do stuff }
            

            文档:https://msdn.microsoft.com/en-us/library/scekt9xw.aspx

            【讨论】:

            • 哇。这在语法上是糖。如果(这是 A 类)
            【解决方案7】:

            你可以只使用 base。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-01-14
              • 1970-01-01
              • 2012-02-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多