How to get MethodInfo for generic extension method?

前端 未结 1 428
遇见更好的自我
遇见更好的自我 2021-01-11 15:47

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

相关标签:
1条回答
  • 2021-01-11 16:28

    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.

    0 讨论(0)
提交回复
热议问题