如何从WinRT中的Action获取方法名称 [英] How to get method name from Action in WinRT

查看:150
本文介绍了如何从WinRT中的Action获取方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the method name from an Action in WinRT, where Action.Method is not available. So far I have this:

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()我得到这个输出:

When I call TestGetMethodName() I get this output:

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?

The goal is to get the name of the method that is assigned to TestDelegate. The "GetMethodName(x => PrintInt(x))" call is only there to prove that I'm doing it at least partly right. How can I get it to tell me that "TestDelegate method name is PrintInt"?

推荐答案

答案比我简单得多进行中。它只是TestDelegate.GetMethodInfo()。名称。不需要我的GetMethodName函数。我不是使用System.Reflection,所以Delegate.GetMethodInfo没有出现在智能感知中,我以某种方式错过了文档。感谢HappyNomad弥补差距。

The answer is much simpler than I was making it. It's simply TestDelegate.GetMethodInfo().Name. No need for my GetMethodName function. I wasn't "using System.Reflection" and so Delegate.GetMethodInfo wasn't appearing in intellisense, and I somehow missed it in the docs. Thanks to HappyNomad for bridging the gap.

工作代码是:

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

这篇关于如何从WinRT中的Action获取方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆