检索泛型方法的正确超负荷的MethodInfo的

编程入门 行业动态 更新时间:2024-10-26 02:25:36
本文介绍了检索泛型方法的正确超负荷的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的

本文发布于:2023-11-05 04:16:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559877.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   MethodInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!