如何从WinRT中的Action获取方法名称

时间:2013-03-26 21:48:40

标签: c# reflection windows-runtime expression

我正在尝试从WinRT中的Action获取方法名称,其中Action.Method不可用。到目前为止,我有这个:

public class Test2
{
    public static Action<int> TestDelegate { get; set; }

    private static string GetMethodName(Expression<Action<int>> e)
    {
        Debug.WriteLine("e.Body.NodeType is {0}", e.Body.NodeType);
        MethodCallExpression mce = e.Body as MethodCallExpression;
        if (mce != null)
        {
            return mce.Method.Name;
        }
        return "ERROR";
    }

    public static void PrintInt(int x)
    {
        Debug.WriteLine("int {0}", x);
    }

    public static void TestGetMethodName()
    {
        TestDelegate = PrintInt;
        Debug.WriteLine("PrintInt method name is {0}", GetMethodName(x => PrintInt(x)));
        Debug.WriteLine("TestDelegate method name is {0}", GetMethodName(x => TestDelegate(x)));
    }
}

当我调用TestGetMethodName()时,我得到了这个输出:

e.Body.NodeType is Call
PrintInt method name is PrintInt
e.Body.NodeType is Invoke
TestDelegate method name is ERROR

目标是获取分配给TestDelegate的方法的名称。 “GetMethodName(x =&gt; PrintInt(x))”调用仅用于证明我至少部分正确地进行了调用。我如何才能告诉我“TestDelegate方法名称是PrintInt”?

2 个答案:

答案 0 :(得分:3)

答案比我做的简单得多。它只是TestDelegate.GetMethodInfo()。名称。不需要我的GetMethodName函数。我没有“使用System.Reflection”,所以Delegate.GetMethodInfo没有出现在intellisense中,我在文档中错过了它。感谢HappyNomad弥合差距。

工作代码是:

public class Test2
{
    public static Action<int> TestDelegate { get; set; }

    public static void PrintInt(int x)
    {
        Debug.WriteLine("int {0}", x);
    }

    public static void TestGetMethodName()
    {
        TestDelegate = PrintInt;
        Debug.WriteLine("TestDelegate method name is {0}", TestDelegate.GetMethodInfo().Name);
    }
}

答案 1 :(得分:1)

private static string GetMethodName( Expression<Action<int>> e )
{
    Debug.WriteLine( "e.Body.NodeType is {0}", e.Body.NodeType );
    MethodCallExpression mce = e.Body as MethodCallExpression;
    if ( mce != null ) {
        return mce.Method.Name;
    }

    InvocationExpression ie = e.Body as InvocationExpression;
    if ( ie != null ) {
        var me = ie.Expression as MemberExpression;
        if ( me != null ) {
            var prop = me.Member as PropertyInfo;
            if ( prop != null ) {
                var v = prop.GetValue( null ) as Delegate;
                return v.Method.Name;
            }
        }
    }
    return "ERROR";
}