2015-04-02 74 views
2

我正在寫一個抽象類(在它的構造函數中)收集所有符合特定簽名的靜態方法。它收集的方法必須是這樣的:使用反射測試方法是否具有特定的簽名

static ConversionMerit NAME(TYPE1, out TYPE2, out string) 

在哪裏我不關心命名,或類型的前兩個參數的,但第二個和第三個參數必須是「出」參數和第三個必須是System.String類型的。

我的問題是與stringness最後檢查:

MethodInfo[] methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); 
    foreach (MethodInfo method in methods) 
    { 
    if (method.ReturnType != typeof(ConversionMerit)) 
     continue; 

    ParameterInfo[] parameters = method.GetParameters(); 
    if (parameters.Length != 3) 
     continue; 

    if (parameters[0].IsOut) continue; 
    if (!parameters[1].IsOut) continue; 
    if (!parameters[2].IsOut) continue; 

    // Validate the third parameter is of type string. 
    Type type3 = parameters[2].ParameterType; 
    if (type3 != typeof(string)) // <-- type3 looks like System.String& 
     continue; 

    // This is where I do something irrelevant to this discussion. 
    } 

第三的ParameterInfo的參數類型物業,告訴我,類型是System.String &,並比較它的typeof(串)失敗。執行此檢查的最佳方法是什麼?這聽起來有點火腿,我比較類型名使用字符串比較。

回答

6

您需要使用MakeByRefType方法得到string&的類型。然後將它與給定類型進行比較。

if (type3 != typeof(string).MakeByRefType()) 
+0

是的!那樣做了。 – 2015-04-02 20:48:05

-1

System.String &如果您的方法參數由ref傳遞或者是out參數,則返回。當一個字符串被正常傳遞,它會顯示爲System.String那麼這將與您相匹配,如果條件

if (type3 != typeof(string)) 

爲了比較REF類型,你可以做到這一點

if (type3 != typeof(string).MakeByRefType()) 
+0

好吧,但我*需要*的參數被引用或輸出,所以如何測試類型以確保它是一個字符串?我已經在前面的條件中測試了'outness',所以剩下的就是類型比較。 – 2015-04-02 20:46:42

+0

正如Selman所述,使用MakeByRefType – 2015-04-02 20:49:38