C#:你如何获得一个类的基类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1105251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:22:11  来源:igfitidea点击:

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

c#superclass

提问by JaysonFix

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

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

For example, suppose you have a certain class, MyClass, and you want to obtain a reference to MyClass' superclass.

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

I have in mind something like this:

我想到了这样的事情:

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

However, it appears there is no suitable GetBasemethod.

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

采纳答案by JoshJordan

Use Reflection from the Type of the current class.

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

 Type superClass = myClass.GetType().BaseType;

回答by 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:

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

Type baseClass = myObject.GetType().BaseType;

documentation

文件

回答by heavyd

The Type.BaseTypeproperty is what you're looking for.

Type.BaseType属性是你在找什么。

Type  superClass = typeof(MyClass).BaseType;

回答by Sergio

you can just use base.

你可以只使用基地。

回答by jason

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.BaseTypeand Activator.CreateInstanceon MSDN.

请参阅MSDN 上的Type.BaseTypeActivator.CreateInstance

回答by meklarian

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

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

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

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

回答by VeYroN

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

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

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

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

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