问题描述
我不会是唯一一个厌倦了为需要委托的单次调用定义和命名委托的人.例如,我想以可能来自其他线程的表单调用 .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# 中的匿名委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!