c# - 使用反射测试方法是否具有特定签名

标签 c# reflection reference-type parameterinfo

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

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())   

关于c# - 使用反射测试方法是否具有特定签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29421982/

相关文章:

c# - Windows Phone 8 页面方向

c# - Entity Framework 中通用类型的文本搜索

c# - 以高压缩级别压缩 JP2 (JPEG2000) 图像

.net - 获取变量(非硬编码)名称?

java - 使用 kotlin 反射将对象成员属性映射到 hashmap 时出现问题

java - 如何在运行可执行 jar 时查找类

C#,将一个 bool 复制到另一个(通过 ref,而不是 val)

swift - Swift 3.0 中如何区分类(确定它不是结构体或枚举)

c# - 为什么字符串作为值类型,即使它是 C# 中的引用类型

c# - MimeKit:如何嵌入图像?