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

2019-03-14 06:56发布

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 reference to MyClass' superclass.

I have in mind something like this:

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

However, it appears there is no suitable GetBase method.

标签: c# superclass
7条回答
太酷不给撩
2楼-- · 2019-03-14 07:23

Use Reflection from the Type of the current class.

 Type superClass = myClass.GetType().BaseType;
查看更多
Emotional °昔
3楼-- · 2019-03-14 07:34
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

查看更多
Ridiculous、
4楼-- · 2019-03-14 07:34

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

查看更多
倾城 Initia
5楼-- · 2019-03-14 07:36

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

Type  superClass = typeof(MyClass).BaseType;
查看更多
可以哭但决不认输i
6楼-- · 2019-03-14 07:38

you can just use base.

查看更多
何必那么认真
7楼-- · 2019-03-14 07:40

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.

查看更多
登录 后发表回答