anonymous delegates in C#(C# 中的匿名委托)
问题描述
我不会是唯一一个厌倦了为需要委托的单次调用定义和命名委托的人.例如,我想以可能来自其他线程的表单调用 .Refresh(),所以我编写了以下代码:
I can't be the only one getting tired of defining and naming a delegate for just a single call to something that requires a delegate. For example, I wanted to call .Refresh() in a form from possibly other threads, so I wrote this code:
private void RefreshForm()
{
if (InvokeRequired)
Invoke(new InvokeDelegate(Refresh));
else
Refresh();
}
我什至不确定我是否必须这样做,我只是读了足够多的书,害怕它在以后的某个阶段不起作用.
InvokeDelegate 实际上是在另一个文件中声明的,但我是否真的需要一个专门用于此的整个委托?根本没有任何通用代表吗?
我的意思是,例如,有一个 Pen 类,但也有 Pens.pen-of-choice 所以你不必重新制作整个东西.不一样,但我希望你明白我的意思.
I'm not even sure I have to, I just read enough to be scared that it won't work at some later stage.
InvokeDelegate is actually declared in another file, but do I really need an entire delegate dedicated just for this? aren't there any generic delegates at all?
I mean, for example, there's a Pen class, but there's also Pens.pen-of-choice so you don't have to remake the whole thing. It's not the same, but I hope you understand what I mean.
推荐答案
是的.在 .NET 3.5 中,您可以使用 Func 和 Action 代表.Func 委托返回一个值,而 Action 委托返回 void.以下是类型名称的样子:
Yes. In .NET 3.5 you can use Func and Action delegates. The Func delegates return a value, while Action delegates return void. Here is what the type names would look like:
System.Func<TReturn> // (no arg, with return value)
System.Func<T, TReturn> // (1 arg, with return value)
System.Func<T1, T2, TReturn> // (2 arg, with return value)
System.Func<T1, T2, T3, TReturn> // (3 arg, with return value)
System.Func<T1, T2, T3, T4, TReturn> // (4 arg, with return value)
System.Action // (no arg, no return value)
System.Action<T> // (1 arg, no return value)
System.Action<T1, T2> // (2 arg, no return value)
System.Action<T1, T2, T3> // (3 arg, no return value)
System.Action<T1, T2, T3, T4> // (4 arg, no return value)
我不知道为什么他们每个都停在 4 个 args 上,但这对我来说一直都足够了.
I don't know why they stopped at 4 args each, but it has always been enough for me.
这篇关于C# 中的匿名委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的匿名委托
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01