![](/img/trans.png)
[英](C#) How do you deal with a Base class with a constructor, when you want to make an inheriting class?
[英]C# : how do you obtain a class' base class?
在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 }
文档: https : //msdn.microsoft.com/en-us/library/scekt9xw.aspx
你可以使用base。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.