在C#中,如何获取对给定类的基类的引用?
例如,假设您有某个类MyClass,并且您想获得对MyClass"超类" 的引用.
我记得这样的事情:
Type superClass = MyClass.GetBase() ;
// then, do something with superClass
Run Code Online (Sandbox Code Playgroud)
但是,似乎没有合适的GetBase方法.
Jos*_*dan 51
使用当前类的类型中的反射.
Type superClass = myClass.GetType().BaseType;
Run Code Online (Sandbox Code Playgroud)
Tim*_*ter 21
Type superClass = typeof(MyClass).BaseType;
Run Code Online (Sandbox Code Playgroud)
此外,如果您不知道当前对象的类型,可以使用GetType获取类型,然后获取该类型的BaseType:
Type baseClass = myObject.GetType().BaseType;
Run Code Online (Sandbox Code Playgroud)
这将获得基类型(如果存在)并创建它的实例:
Type baseType = typeof(MyClass).BaseType;
object o = null;
if(baseType != null) {
o = Activator.CreateInstance(baseType);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您在编译时不知道类型,请使用以下命令:
object myObject;
Type baseType = myObject.GetType().BaseType;
object o = null;
if(baseType != null) {
o = Activator.CreateInstance(baseType);
}
Run Code Online (Sandbox Code Playgroud)
见Type.BaseType和Activator.CreateInstanceMSDN上.