Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#:如何获得一个类';基类?_C#_Superclass - Fatal编程技术网

C#:如何获得一个类';基类?

C#:如何获得一个类';基类?,c#,superclass,C#,Superclass,在C#中,如何获得对给定类的基类的引用 例如,假设您有一个特定的类,MyClass,并且希望获得对MyClass”超类的引用 我有这样的想法: Type superClass = MyClass.GetBase() ; // then, do something with superClass 但是,似乎没有合适的GetBase方法 Type superClass = typeof(MyClass).BaseType; 此外,如果不知道当前对象的类型,可以使用GetType获取该类型,然后

在C#中,如何获得对给定类的基类的引用

例如,假设您有一个特定的类,
MyClass
,并且希望获得对
MyClass
”超类的引用

我有这样的想法:

Type  superClass = MyClass.GetBase() ;
// then, do something with superClass
但是,似乎没有合适的
GetBase
方法

Type superClass = typeof(MyClass).BaseType;
此外,如果不知道当前对象的类型,可以使用GetType获取该类型,然后获取该类型的BaseType:

Type baseClass = myObject.GetType().BaseType;

您要找的就是这家酒店

Type  superClass = typeof(MyClass).BaseType;

使用当前类类型的反射

 Type superClass = myClass.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上的和。

obj.base将从派生对象obj的实例获取对父对象的引用


typeof(obj)。BaseType将从派生对象obj的实例获取对父对象类型的引用。

如果要检查某个类是否是另一个类的子类,可以使用is

if (variable is superclass){ //do stuff }

文档:

base
this
仅在instance methods.Wauw中可用。这是语法上的糖。如果(这是A类)