2012-09-10 65 views
11

我有以下分類:C#GetMethod不返回父類的方法

public class A 
{ 
    public static object GetMe(SomeOtherClass something) 
    { 
     return something.Foo(); 
    } 
} 

public class B:A 
{ 
    public static new object GetMe(SomeOtherClass something) 
    { 
     return something.Bar(); 
    } 
} 

public class C:B 
{ 

} 

public class SomeOtherClass 
{ 

} 

鑑於SomeOtherClass parameter = new SomeOtherClass())這個作品:

typeof(B).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter)); 

但這:

typeof(C).GetMethod("GetMe", new Type[] { typeof(SomeOtherClass) })).Invoke(null, parameter)); 

拋出一個NullReferenceException,而我希望它會調用與上面完全相同的方法。

我試過幾個綁定標誌無濟於事。任何幫助?

回答

19

您應該使用overloads之一,參數爲BindingFlags,並且包括FlattenHierarchy

指定應返回層次結構中公共和受保護的靜態成員。不會返回繼承類中的私有靜態成員。靜態成員包括字段,方法,事件和屬性。嵌套類型不返回。

(編輯刪除有關私人靜態方法的地步,現在的問題已經改變向公衆發佈。)

+0

這些方法是公共靜態的,我錯誤地鍵入了問題(我認爲我有證據讀它D :)。還是謝謝! –

+1

@SebastiánVansteenkiste:在這種情況下,只需將綁定標誌更改爲包含FlattenHierarchy(以及static和public)即可。 –

+0

非常感謝!對於後代,則:'typeof(C).GetMethod(「GetMe」,BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static,null,new Type [] {typeof(SomeOtherClass)},null))。Invoke(null ,參數));'做了訣竅。 –

4

您需要BindingFlags.FlattenHierarchy標誌傳遞給GetMethod爲了尋找了層次:

typeof(C).GetMethod("GetMe", BindingFlags.FlattenHierarchy, null, new Type[] { typeof(SomeOtherClass) }, null)).Invoke(null, parameter)); 
+0

我似乎錯過了'FlattenHierarchy' ..謝謝,我現在就試試! –

+1

不僅添加'FlattenHierarchy',而且'Public'和'Static'解決了它。 –