【发布时间】:2021-01-24 13:22:12
【问题描述】:
我尝试在静态类中获取运行时方法信息。我在类中有四个静态方法,每个名称都相等,参数名称也相等。唯一的区别是它们的类型。四种方法之一具有字符串参数,因此很容易获取方法信息。然而其他人不工作。我找到了一些建议,但都不起作用。
所有测试代码都在这里。
class Program {
static void Main(string[] args) {
//ok
var stringMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(string) });
//not working
var dictMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(Dictionary<,>) });
//not working
var genericMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(object) });
//not working
var listMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(List<>) });
//not working
var res = typeof(TestClass)
.GetRuntimeMethods()
.Where(x => x.Name.Equals("TestMethod"))
.Select(m => new { Method = m, Parameters = m.GetParameters() })
.FirstOrDefault(p =>
p.Parameters.Length == 1
&& p.Parameters[0].ParameterType.IsGenericType
&& p.Parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(ICollection<>)
);
}
}
public static class TestClass {
public static bool TestMethod(string item) {
return true;
}
public static bool TestMethod<TKey, TValue>(Dictionary<TKey, TValue> item) {
return true;
}
public static bool TestMethod<T>(T item) {
return true;
}
public static bool TestMethod<T>(List<T> item) {
return true;
}
}
【问题讨论】:
-
“不工作”到底是什么意思?
-
返回空值。当只有一个具有相同名称或不同数量的参数等的泛型时,它们正在工作。在我的场景中,我总是得到空值。在代码中, res 行是 stackoverflow 的一个示例。它也是返回 null
-
抱歉,您希望它返回什么?它将返回第一个
TestMethod,其中恰好有通用参数,其通用定义为ICollection<>。你没有这种方法。 -
好的。什么是字典?我如何获得每个方法信息?显然,除了字符串参数外,我无法获取方法信息。所以我试着理解为什么?解决方案是什么?
标签: c# system.reflection methodinfo