获取强类型方法的名称

时间:2013-09-14 09:21:00

标签: c# reflection lambda

认为我有一个如下课程:

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;
    }
}

所有你知道我可以编写一个返回给定属性名称的方法:

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

GetPropertyName方法可以轻松实现,如下所示:

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;
}

但我想像下面的属性名一样轻松获取方法名称:

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

是否可以编写这样的GetMethodName方法?

请注意:GetMethodName必须独立于给定方法的签名或返回值。

1 个答案:

答案 0 :(得分:7)

经过一些研究,我发现Expression<Action<T>>应足以做你想做的事。

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;
    }
}

Output

相关问题