【问题标题】:Testing whether a method has a specific signature using Reflection使用反射测试方法是否具有特定签名
【发布时间】:2015-06-07 22:35:16
【问题描述】:

我正在编写一个抽象类,它(在其构造函数中)收集所有符合特定签名的静态方法。它收集的方法必须如下所示:

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) 进行比较失败。执行此检查的最佳方法是什么?使用字符串比较来比较类型名对我来说听起来有点笨拙。

【问题讨论】:

    标签: c# reflection reference-type parameterinfo


    【解决方案1】:

    你需要使用MakeByRefType方法来获取string&amp;的类型。然后与给定的类型进行比较。

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

    【讨论】:

      【解决方案2】:

      如果您的方法参数由 ref 传递或者是 out 参数,则返回 System.String&。当一个字符串正常传递时,它会显示为 System.String ,然后匹配你的 if 条件

      if (type3 != typeof(string)) 
      

      为了比较 ref 类型,你可以这样做

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

      【讨论】:

      • 好的,但是我 需要 参数是 ref 或 out,那么如何测试类型以确保它是字符串?我已经在前面的条件中测试了“outness”,所以剩下的就是类型比较了。
      猜你喜欢
      • 2014-12-09
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多