如何传递方法名称以实例化委托?

Edw*_*uay 2 c# delegates

在下面的示例中,我想定义一个System.Action,它执行我在运行时定义的特定方法,但是如何传递方法名称(或方法本身),以便Action方法可以定义委托指向那个特别的方法?

我目前收到以下错误:

'methodName'是'变量',但用作'方法'

using System;
using System.Collections.Generic;

namespace TestDelegate
{
    class Program
    {
        private delegate void WriteHandler(string message);

        static void Main(string[] args)
        {
            List<string> words = new List<string>() { "one", "two", "three", "four", "five" };
            Action<string> theFunction = WriteMessage("WriteBasic");

            foreach (string word in words)
            {
                theFunction(word);
            }
            Console.ReadLine();
        }

        public static void WriteBasic(string message)
        {
            Console.WriteLine(message);
        }

        public static void WriteAdvanced(string message)
        {
            Console.WriteLine("*** {0} ***", message);
        }

        public static Action<string> WriteMessage(string methodName)
        {
            //gets error: 'methodName' is a 'variable' but is used like a 'method'
            WriteHandler writeIt = new WriteHandler(methodName);

            return new Action<string>(writeIt);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Mla*_*vic 5

您不需要Delegate声明或WriteMessage方法.请尝试以下方法:

using System;
using System.Collections.Generic;

namespace TestDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> words = new List<string>() { "one", "two", "three", "four", "five" };
            Action<string> theFunction = WriteBasic;

            foreach (string word in words)
            {
                theFunction(word);
            }
            Console.ReadLine();
        }

        public static void WriteBasic(string message)
        {
            Console.WriteLine(message);
        }

        public static void WriteAdvanced(string message)
        {
            Console.WriteLine("*** {0} ***", message);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Action已经是一个委托,因此您无需再制作另一个委托.