2011-04-25 75 views
88

從基類調用時,GetType()是否返回派生類型最多?從基類中調用GetType()是否返回派生類型最多?

例子:

public abstract class A 
{ 
    private Type GetInfo() 
    { 
     return System.Attribute.GetCustomAttributes(this.GetType()); 
    } 
} 

public class B : A 
{ 
    //Fields here have some custom attributes added to them 
} 

或者我應該只是使派生類必須實現象下面的抽象方法?

public abstract class A 
{ 
    protected abstract Type GetSubType(); 

    private Type GetInfo() 
    { 
     return System.Attribute.GetCustomAttributes(GetSubType()); 
    } 
} 

public class B : A 
{ 
    //Fields here have some custom attributes added to them 

    protected Type GetSubType() 
    { 
     return GetType(); 
    } 
} 
+8

好 - 你試過嗎? – BrokenGlass 2011-04-25 16:40:58

+1

@BrokenGlass通常我會這樣做,但我不在電腦......只是用我的手機來發帖,因爲問題的解決方案已經開始形成,我很想知道現在! = P – 2011-04-25 16:43:11

回答

98

GetType()將返回實際的,實例化的類型。在你的情況下,如果你在B的實例上調用GetType(),它將返回typeof(B),即使所討論的變量被聲明爲對A的引用。

沒有理由爲您的GetSubType()方法。

16

GetType總是返回實際實例化的類型。即最派生的類型。這意味着您的GetSubType行爲就像GetType本身,因此是不必要的。

要靜態獲取某種類型的信息,您可以使用typeof(MyClass)

雖然您的代碼有一個錯誤:System.Attribute.GetCustomAttributes返回Attribute[]而不是Type

7

GetType總是返回實際的類型。

其原因是在.NET框架和CLR深,如JIT和CLR使用.GetType方法在內存中創建一個Type對象保存在對象上的信息,所有訪問對象和編譯是通過這個Type實例。

欲瞭解更多信息,請參閱Microsoft Press出版的「CLR via C#」一書。

相關問題