反思:如何获取MethodInfo的泛型扩展方法? [英] Reflection: how to get MethodInfo for generic extension method?

查看:111
本文介绍了反思:如何获取MethodInfo的泛型扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的IEnumerable< T> ,我想调用的 Enumerable.Contains 通过反射法。我只是努力获得的语法正确。这是我目前有:

  VAR containsMethod = typeof运算(可枚举).GetMethod(包含,
新[ ] {
的typeof(IEnumerable的< T>),
的typeof(T)
});

这只是回来了空。



什么是让的MethodInfo


解决方案
的正确方法

什么是获取MethodInfo的正确方法是什么?




您必须找到的通用的方法 - 这是不幸的是有点痛 - 然后构造使用适当的参数。在这种情况下,你知道,只有2 包含重载,你想一个有两个参数,所以你可以使用:

  VAR方法= typeof运算(可枚举).GetMethods()
。凡(M = GT; m.Name ==包含)
。单(M = GT; m.GetParameters()==长度2)
.MakeGenericMethod(typeof运算(T));

您应该然后能够适当地调用它。


I have an IEnumerable<T>, and I want to call the Enumerable.Contains method by reflection. I'm just struggling to get the syntax right. Here's what I currently have:

var containsMethod = typeof(Enumerable).GetMethod("Contains", 
  new[] {
    typeof(IEnumerable<T>), 
    typeof(T) 
  });

This just comes back with a null.

What is the correct way to get the MethodInfo?

解决方案

What is the correct way to get the MethodInfo?

You have to find the generic method - which is unfortunately a bit of a pain - and then construct that with the appropriate arguments. In this case you know that there are only 2 Contains overloads, and the one you want has two arguments, so you can use:

var method = typeof(Enumerable).GetMethods()
                               .Where(m => m.Name == "Contains")
                               .Single(m => m.GetParameters().Length == 2)
                               .MakeGenericMethod(typeof(T));

You should then be able to invoke it appropriately.

这篇关于反思:如何获取MethodInfo的泛型扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆