开发者

Select method expression using lambda syntax ignoring overloads

开发者 https://www.devze.com 2023-01-29 20:57 出处:网络
I currently use the following extension method in order to select a method: public static Method开发者_如何学GoInfo GetMethod<TType>(this TType type,

I currently use the following extension method in order to select a method:

    public static Method开发者_如何学GoInfo GetMethod<TType>(this TType type, 
                           Expression<Action<TType>> methodSelector) 
                           where TType : class
    {
        return ((MethodCallExpression)methodSelector.Body).Method;
    }

This is called like this:

this.GetMethod(x => x.MyMethod(null,null))

It doesn't matter to me which method I'm selecting, I'm simply using this as way to get the method name in a strongly-typed way. Is there a way that I can still select the method using the lambda syntax but not specify any arguments?

I.e.

 this.GetMethod(x => x.MyMethod)


This seems to work, but with the added cost of having to specify signatures for methods which take parameters. I couldn't work out how to get those automatically.

public static class ObjectExtensions
{
    public static MethodInfo GetMethod<TType, TSignature>(this TType type, Expression<Func<TType, TSignature>> methodSelector) where TType : class
    {
        var argument = ((MethodCallExpression)((UnaryExpression)methodSelector.Body).Operand).Arguments[2];
        return ((ConstantExpression)argument).Value as MethodInfo;
    }

    public static MethodInfo GetMethod<TType>(this TType type, Expression<Func<TType, Action>> methodSelector) where TType : class
    {
        return GetMethod<TType, Action>(type, methodSelector);
    }
}

Tested with this simple example:

public class MyClass
{
    public static void RunTest()
    {
        var m = new MyClass().GetMethod(x => x.Test);
        Console.WriteLine("{0}", m);

        m = new MyClass().GetMethod<MyClass, Action<int>>(x => x.Test2);
        System.Console.WriteLine("{0}", m);
        Console.ReadKey();
    }

    public void Test()
    {
    }

    public void Test2(int a)
    {
    }
}
0

精彩评论

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