2009-07-09 64 views
31

在C#中,如何獲得對給定類的基類的引用?C#:你如何獲得一個類的基類?

例如,假設您有某個類MyClass,並且您想要獲得對MyClass超類的引用。

我想到的是這樣的:

Type superClass = MyClass.GetBase() ; 
// then, do something with superClass 

然而,似乎沒有合適的GetBase方法。

回答

44

使用來自當前類的類型的反射。

Type superClass = myClass.GetType().BaseType; 
20
Type superClass = typeof(MyClass).BaseType; 

此外,如果你不知道你的當前對象的類型,你可以得到它的使用的GetType類型,然後獲得該類型的基本類型:

Type superClass = myObject.GetType().BaseType; 

documentation

-1

你可以使用基地。

5

這將讓基本類型(如果存在的話),並創建它的一個實例:

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); 
} 

請參閱Type.BaseTypeActivator.CreateInstance在MSDN上。

2

obj.base將從派生對象obj的實例中獲取對父對象的引用。

的typeof(OBJ).BaseType將讓你的父對象的類型的引用從派生對象OBJ的一個實例。

+0

`base`和`this`只在實例方法可用。 – 2014-01-27 11:28:36

相關問題