0

我正在尝试从 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 => PrintInt(x))” 调用只是为了证明我做的至少部分正确。我怎样才能让它告诉我“TestDelegate 方法名称是 PrintInt”?

4

2 回答 2

3

答案比我做的要简单得多。它只是 TestDelegate.GetMethodInfo().Name。不需要我的 GetMethodName 函数。我没有“使用 System.Reflection”,所以 Delegate.GetMethodInfo 没有出现在智能感知中,我不知何故在文档中错过了它。感谢 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);
    }
}
于 2013-03-26T22:44:33.703 回答
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";
}
于 2013-03-26T22:12:42.633 回答