本文介绍了检索泛型方法的正确超负荷的MethodInfo的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个类型包含一个通用方法的两个重载。我想找回重载之一(与 Func键< 参数; T&GT)使用反射。但问题是,我无法找到正确的参数类型与供给 Type.GetMethod(字符串类型[])方法。
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.
下面是我的类定义:
public class Foo { public void Bar<T>(Func<T> f) { } public void Bar<T>(Action<T> a) { } }
这是我想出来的,可惜没有更迭:
And this is what I've come up with, unfortunately without succes:
[TestMethod] public void Test1() { Type parameterType = typeof(Func<>); var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType }); Assert.IsNotNull(method); // Fails }
我怎样才能获得的MethodInfo 的通用方法,我知道的参数?
How can I get the MethodInfo of a generic method of which I know the parameters?
推荐答案你为什么不使用EX pression树?这使得它更容易:
Why don't you use expression trees? This makes it much easier:
public static MethodInfo GetMethod<T>( Expression<Action<T>> methodSelector) { var body = (MethodCallExpression)methodSelector.Body; return body.Method; } [TestMethod] public void Test1() { var expectedMethod = typeof(Foo) .GetMethod("Bar", new Type[] { typeof(Func<>) }); var actualMethod = GetMethod<Foo>(foo => foo.Bar<object>((Func<object>)null) .GetGenericMethodDefinition(); Assert.AreEqual(expectedMethod, actualMethod); }更多推荐
检索泛型方法的正确超负荷的MethodInfo的
发布评论