gpt4 book ai didi

c# - 如何传递方法名称以实例化委托(delegate)?

转载 作者:行者123 更新时间:2023-11-30 19:51:42 24 4
gpt4 key购买 nike

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

我目前遇到以下错误:

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

}
}

最佳答案

您不需要委托(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);
}

}
}

Action 已经是一个委托(delegate),所以你不需要再做一个。

关于c# - 如何传递方法名称以实例化委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/760503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com