C# 如何传递方法名以实例化委托?
在下面的示例中,我想定义一个System.Action,它执行我在运行时定义的特定方法,但是如何传递方法名(或方法本身),以便Action方法可以定义指向该特定方法的委托 我当前遇到以下错误: “methodName”是一个“变量”,但与“方法”一样使用C# 如何传递方法名以实例化委托?,c#,delegates,C#,Delegates,在下面的示例中,我想定义一个System.Action,它执行我在运行时定义的特定方法,但是如何传递方法名(或方法本身),以便Action方法可以定义指向该特定方法的委托 我当前遇到以下错误: “methodName”是一个“变量”,但与“方法”一样使用 使用系统; 使用System.Collections.Generic; 命名空间TestDelegate { 班级计划 { 私有委托void WriteHandler(字符串消息); 静态void Main(字符串[]参数) { 列表词=新列表
使用系统;
使用System.Collections.Generic;
命名空间TestDelegate
{
班级计划
{
私有委托void WriteHandler(字符串消息);
静态void Main(字符串[]参数)
{
列表词=新列表({“一”、“二”、“三”、“四”、“五”});
操作函数=写消息(“写基”);
foreach(单词中的字符串)
{
函数(word);
}
Console.ReadLine();
}
公共静态无效写基(字符串消息)
{
控制台写入线(消息);
}
公共静态void WriteAdvanced(字符串消息)
{
Console.WriteLine(“***{0}***”,消息);
}
公共静态操作WriteMessage(string methodName)
{
//获取错误:“methodName”是“变量”,但与“方法”一样使用
WriteHandler writeIt=新的WriteHandler(方法名);
返回新操作(writeIt);
}
}
}
除非使用反射,否则无法通过这样的方法。为什么不使用WriteHandler作为参数而不是字符串?您可以让它与反射一起工作,但不建议这样做
为什么不让WriteMessage方法接受WriteHandler的参数呢
然后你可以这样称呼它(在C#2+中):
不加引号地传递它-
Action<string> theFunction = WriteMessage(WriteBasic);
您不需要委托声明或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);
}
}
}
使用系统;
使用System.Collections.Generic;
命名空间TestDelegate
{
班级计划
{
静态void Main(字符串[]参数)
{
列表词=新列表({“一”、“二”、“三”、“四”、“五”});
操作函数=写基;
foreach(单词中的字符串)
{
函数(word);
}
Console.ReadLine();
}
公共静态无效写基(字符串消息)
{
控制台写入线(消息);
}
公共静态void WriteAdvanced(字符串消息)
{
Console.WriteLine(“***{0}***”,消息);
}
}
}
操作已经是一个委托,因此您不需要再做一个。您需要的。在您的具体情况下,您可能需要:
公共静态行为
Action<string> theFunction = WriteMessage(WriteBasic);
public static Action<string> WriteMessage(WriteHandler methodName)
public delegate void WriteHandler(string message); //Edit suggested by Mladen Mihajlovic
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);
}
}
}
public static Action<string> WriteMessage(string methodName)
{
return (Action<string>) Delegate.CreateDelegate (
typeof(Action<string>),
typeof(Program),
methodName);
}