【发布时间】:2010-11-09 11:13:08
【问题描述】:
在 C# 中,如何获得对给定类的基类的引用?
例如,假设你有一个特定的类MyClass,并且你想获得对MyClass'超类的引用。
我有这样的想法:
Type superClass = MyClass.GetBase() ;
// then, do something with superClass
但是,似乎没有合适的GetBase 方法。
【问题讨论】:
标签: c# superclass
在 C# 中,如何获得对给定类的基类的引用?
例如,假设你有一个特定的类MyClass,并且你想获得对MyClass'超类的引用。
我有这样的想法:
Type superClass = MyClass.GetBase() ;
// then, do something with superClass
但是,似乎没有合适的GetBase 方法。
【问题讨论】:
标签: c# superclass
从当前类的类型中使用反射。
Type superClass = myClass.GetType().BaseType;
【讨论】:
Type superClass = typeof(MyClass).BaseType;
另外,如果不知道当前对象的类型,可以使用GetType获取类型,然后获取该类型的BaseType:
Type baseClass = myObject.GetType().BaseType;
【讨论】:
这将获取基本类型(如果存在)并创建它的实例:
Type baseType = typeof(MyClass).BaseType;
object o = null;
if(baseType != null) {
o = Activator.CreateInstance(baseType);
}
或者,如果您在编译时不知道类型,请使用以下内容:
object myObject;
Type baseType = myObject.GetType().BaseType;
object o = null;
if(baseType != null) {
o = Activator.CreateInstance(baseType);
}
请参阅 MSDN 上的 Type.BaseType 和 Activator.CreateInstance。
【讨论】:
Type.BaseType 属性是您正在寻找的。p>
Type superClass = typeof(MyClass).BaseType;
【讨论】:
obj.base 将从派生对象 obj 的实例中获取对父对象的引用。
typeof(obj).BaseType 将从派生对象 obj 的实例中获取对父对象类型的引用。
【讨论】:
base 和 this 仅在实例方法中可用。
如果你想检查一个类是否是另一个类的子类,你可以使用 is。
if (variable is superclass){ //do stuff }
【讨论】:
你可以只使用 base。
【讨论】: