在C#中,如何获取对给定类的基类的引用?
例如,假设您有一个特定的类MyClass
,并且您想获得对MyClass
'超类的引用。
我记得这样的事情:
Type superClass = MyClass.GetBase() ;
// then, do something with superClass
然而,似乎没有合适的GetBase
方法。
使用当前类的类型中的反射。
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酒店是您正在寻找的。
Type superClass = typeof(MyClass).BaseType;
obj.base将从派生对象obj的实例中获取对父对象的引用。
typeof(obj).BaseType将从派生对象obj的实例中获取对父对象类型的引用。
如果你想检查一个类是否是你可以使用的另一个的子类。
if (variable is superclass){ //do stuff }
你可以使用base。