开发者

Reflection: How to get a generic method? [duplicate]

开发者 https://www.devze.com 2023-02-15 10:33 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: How to use reflection to call generic Method?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How to use reflection to call generic Method?

Select Right Generic Method with Reflection

Hi there

Let's say I have two following two methods in a class:

public void MyMethod(object val) {}
public void MyMethod<T>(T val) {}

With reflection, I could get the fir开发者_运维知识库st Method like this:

Type[] typeArray = new Type[1];
typeArray.SetValue(typeof(object), 1);
var myMethod = myInstance.GetType().GetMethod("MyMethod", typeArray);

But how can I get the second, generic method?


var myMethod = myInstance.GetType()
                         .GetMethods()
                         .Where(m => m.Name == "MyMethod")
                         .Select(m => new {
                                              Method = m,
                                              Params = m.GetParameters(),
                                              Args = m.GetGenericArguments()
                                          })
                         .Where(x => x.Params.Length == 1
                                     && x.Args.Length == 1
                                     && x.Params[0].ParameterType == x.Args[0])
                         .Select(x => x.Method)
                         .First();


I would do it like this:

var methods = from m in typeof(MyClass).GetMethods()
              where m.Name == "MyMethod"
                 && m.IsGenericMethodDefinition

              let typeParams = m.GetGenericArguments()
              let normalParams = m.GetParameters()

              where typeParams.Length == 1 && normalParams.Length == 1
                 && typeParams.Single() == normalParams.Single().ParameterType
                 && !typeParams.Single().GetGenericParameterConstraints().Any()

              select m;

var myMethod = methods.Single();

We're looking for a method called "MyMethod" that is a generic method with a single type-parameter having no constraints, and one 'normal' parameter of the same type as the type-parameter.

Obviously, if you're not looking to be very precise, you can just do the bare minimum to disambiguate, such as:

var myMethod = typeof(MyClass)
              .GetMethods()
              .Single(m => m.Name == "MyMethod" && m.IsGenericMethodDefinition);
0

精彩评论

暂无评论...
验证码 换一张
取 消