如何设置委托参数的值以用于后续调用而无需每次都提供它们?

问题描述

在 C# 中,有没有办法创建一个带有值的委托,例如"MyDelegate("Hello World")",它可以存储在一个变量中,然后用它给定的值调用

例如:(我知道这不是委托的工作方式,它只是伪代码,可以更清楚地说明我在寻找什么)

delegate void MyDelegate(string text);

void WriteText(string text) 
{
    Console.WriteLine(text)
}

MyDelegate newDelegate = WriteText("Hello World") //Store the function and a string value 

newDelegate.InvokeWithOwnValue() //Invoke the delegate with the string value that we've given it before

//Output: "Hello World"

我不知道这对代表是否可行,或者我是否真的在寻找其他东西。

解决方法

您可以使用 closures

Action newDelegate = () => WriteText("Hello World");
newDelegate();  
,

您可以使用 lambda 来捕获值,但是您需要不同的委托类型,因为现在您将不带参数进行调用。

使用各种 ActionFunc 委托类型要容易得多。

void WriteText(string text) 
{
    Console.WriteLine(text);
}
Action newDelegate = () => WriteText("Hello World"); //Store a string value 

newDelegate(); //Invoke the delegate with the string value that we've given it before

//Output: "Hello World"
Action<string> originalDelegate = WriteText;  // if you already have a delegate

Action newDelegate = () => originalDelegate("Hello World"); //Store the delegate and a string value 

newDelegate(); //Invoke the delegate with the string value that we've given it before

//Output: "Hello World"