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