问题描述
我不能唯一一个厌倦了定义和命名一个委托,只需要一个需要委托的东西的调用。例如,我想以可能的其他线程的形式调用.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实际上是在另一个文件中声明的,但是我真的需要一个专门为此而设的专门委员吗?是不是有任何一般的代表?
我的意思是,例如,有一个笔类,但也有笔。选择,所以你不不得不重塑整件事情。这是不一样的,但我希望你明白我的意思。
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代表返回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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!