如何解决如何设置委托参数的值以用于后续调用而无需每次都提供它们?
在 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 来捕获值,但是您需要不同的委托类型,因为现在您将不带参数进行调用。
使用各种 Action
和 Func
委托类型要容易得多。
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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。