简体   繁体   中英

How to get delegate name inside delegated method?

How to get delegate name inside delegated method?

Here is my program for testing:

namespace Test
{
    class Program
    {
        public Action action;

        void real()
        {
            // I hoped it would output "action" here, but it was "real"
            Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
        }

        public Program()
        {
            action = real;
        }

        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.action();
        }
    }
}

So how can I get the name of delegate action instead of method read ?

I've tried MethodInfo.GetCurrentMethod() , but it didn't work.

Consider

static void Main(string[] args)
{
    Program pr = new Program();
    Action tempName1 = pr.action;
    Action tempName2 = tempName1;

    //pr.action();
    tempName2();
}

Which name would you like to get? tempName1, tempName2, pr.action or just action?

From these choices it follows that you can't get an unambiguous variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM