简体   繁体   中英

Get name of a method strongly typed

Think that I have a class like below:

public class Foo
{
    public int Bar { get; set; }

    public int Sum(int a, int b)
    {
        return a + b;
    }

    public int Square(int a)
    {
        return a * a;
    }
}

All you know that i can write a method that returns name of given property:

var name = GetPropertyName<Foo>(f => f.Bar); //returns "Bar"

GetPropertyName method can be implemented easily as below:

public static string GetPropertyName<T>(Expression<Func<T, object>> exp)
{
    var body = exp.Body as MemberExpression;
    if (body == null)
    {
        var ubody = (UnaryExpression)exp.Body;
        body = ubody.Operand as MemberExpression;
    }
    return body.Member.Name;
}

But I want to get a method name as easily as property name like below:

var name1 = GetMethodName<Foo>(f => f.Sum); //expected to return "Sum"
var name2 = GetMethodName<Foo>(f => f.Square); //expected to return "Square"

Is it possible to write such a GetMethodName method?

Note that: GetMethodName must be independent from signature or return value of the given method.

After some research, I've found that Expression<Action<T>> should be sufficient to do what you want.

private string GetMethodName<T>(Expression<Action<T>> method)
{
    return ((MethodCallExpression)method.Body).Method.Name;
}

public void TestMethod()
{
    Foo foo = new Foo();
    Console.WriteLine(GetMethodName<Foo>(x => foo.Square(1)));
    Console.WriteLine(GetMethodName<Foo>(x => foo.Sum(1,1)));
    Console.ReadLine();
}

public class Foo
{
    public int Bar { get; set; }

    public int Sum(int a, int b)
    {
        return a + b;
    }

    public int Square(int a)
    {
        return a * a;
    }
}

产量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM