簡體   English   中英

使用反射測試方法是否具有特定簽名

[英]Testing whether a method has a specific signature using Reflection

我正在寫一個抽象類(在其構造函數中),該類收集遵循特定簽名的所有靜態方法。 它收集的方法必須類似於:

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

我不在乎命名或前兩個參數的類型的地方,但是第二個和第三個參數必須是“ out”參數,第三個必須是System.String類型。

我的問題是對字符串的最終檢查:

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的ParameterType屬性告訴我類型為System.String&,並將其與typeof(string)比較失敗。 進行此檢查的最佳方法是什么? 對於我來說,使用字符串比較來比較類型名稱聽起來有些束手無策。

您需要使用MakeByRefType方法來獲取string&的類型,然后將其與給定類型進行比較。

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

如果您的方法參數由ref傳遞或為out參數,則返回System.String&。 正常傳遞字符串時,它將顯示為System.String,它將與您的if條件匹配

if (type3 != typeof(string)) 

為了比較引用類型,您可以執行此操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM