C# : how do you obtain a class' base class?

前端 未结 7 1669
面向向阳花
面向向阳花 2021-02-05 00:36

In C#, how does one obtain a reference to the base class of a given class?

For example, suppose you have a certain class, MyClass, and you want to obtain a

相关标签:
7条回答
  • 2021-02-05 01:07

    The Type.BaseType property is what you're looking for.

    Type  superClass = typeof(MyClass).BaseType;
    
    0 讨论(0)
  • 2021-02-05 01:11

    obj.base will get you a reference to the parent object from an instance of the derived object obj.

    typeof(obj).BaseType will get you a reference to the parent object's type from an instance of the derived object obj.

    0 讨论(0)
  • 2021-02-05 01:16
    Type superClass = typeof(MyClass).BaseType;
    

    Additionally, if you don't know the type of your current object, you can get the type using GetType and then get the BaseType of that type:

    Type baseClass = myObject.GetType().BaseType;
    

    documentation

    0 讨论(0)
  • 2021-02-05 01:16

    This will get the base type (if it exists) and create an instance of it:

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

    Alternatively, if you don't know the type at compile time use the following:

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

    See Type.BaseType and Activator.CreateInstance on MSDN.

    0 讨论(0)
  • 2021-02-05 01:17

    Use Reflection from the Type of the current class.

     Type superClass = myClass.GetType().BaseType;
    
    0 讨论(0)
  • 2021-02-05 01:20

    you can just use base.

    0 讨论(0)
提交回复
热议问题