How to find an overloaded method by reflection

女生的网名这么多〃 提交于 2019-12-07 06:34:58

问题


This is a question associated with another question I asked before. I have an overloaded method:

public void Add<T>(SomeType<T> some) { }

public void Add<T>(AnotherType<T> another) { }

How can I find each method by reflection? e.g. How can I get the Add<T>(SomeType<T> some) method by reflection? Can you help me please? Thanks in advance.


回答1:


The trick here is describing that you want the parameter to be SomeType<T>, where T is the generic type of the Add method.

Other than that, it's just about using standard reflection, like CastroXXL suggested in his answer.

Here's how I did it:

var theMethodISeek = typeof(MyClass).GetMethods()
    .Where(m => m.Name == "Add" && m.IsGenericMethodDefinition)
    .Where(m =>
            {
                // the generic T type
                var typeT = m.GetGenericArguments()[0];

                // SomeType<T>
                var someTypeOfT = 
                    typeof(SomeType<>).MakeGenericType(new[] { typeT });

                return m.GetParameters().First().ParameterType == someTypeOfT;
            })
    .First();



回答2:


Look into the MethodInfo Members: http://msdn.microsoft.com/en-US/library/system.reflection.methodinfo_members(v=vs.80).aspx

There are helper properties for IsGenericMethodDefinition and GetParameters. Both could help you figure out what function is what.



来源:https://stackoverflow.com/questions/10464898/how-to-find-an-overloaded-method-by-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!