我正在尝试从 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”?