在下面的例子中,我想定義它執行的是我在運行時定義一個特定的方法System.Action,但如何傳遞方法名稱(或方法本身),所以操作方法可以定義委託來指出特定的方法?如何傳遞一個方法名來實例化一個委託?
目前,我發現了以下錯誤:
「方法名」是一個「變量」,而是使用類似「方法」
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);
}
}
}