2

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

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

4

2 回答 2

6

您需要使用MakeByRefType方法来获取类型。string&然后将其与给定类型进行比较。

 if (type3 != typeof(string).MakeByRefType())   
于 2015-04-02T20:47:02.633 回答
-1

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

if (type3 != typeof(string)) 

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

if (type3 != typeof(string).MakeByRefType()) 
于 2015-04-02T20:42:45.750 回答