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

感情迁移 提交于 2019-12-03 01:03:16

Use Reflection from the Type of the current class.

 Type superClass = myClass.GetType().BaseType;
Timothy Carter
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

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.

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

Type  superClass = typeof(MyClass).BaseType;

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.

if you want to check if a class is subclass of another you can use is.

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

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

you can just use base.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!