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
C# : how do you obtain a class' base class?
提问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 GetBase
method.
但是,似乎没有合适的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;
回答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.BaseType
and Activator.CreateInstance
on MSDN.
请参阅MSDN 上的Type.BaseType
和Activator.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