在C#匿名委托 [英] anonymous delegates in 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在另一个文件实际上宣告,但我的真正的需要专门只为这一个完整的代表?不存在任何泛型委托呢?结果
我的意思是,例如,有一个笔类,但也有笔。笔的选的让你不要重拍整个事情。这是不一样的,但我希望你明白我的意思。
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键代表返回一个值,而行动委托返回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#匿名委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!