c# - C# 中的匿名委托(delegate)

标签 c# delegates anonymous-methods

我不会是唯一一个厌倦了定义和命名委托(delegate)的人,只需一次调用就需要委托(delegate)。例如,我想以可能来自其他线程的形式调用 .Refresh(),因此我编写了以下代码:

private void RefreshForm()
{
    if (InvokeRequired)
        Invoke(new InvokeDelegate(Refresh));
    else
        Refresh();
}

我什至不确定我必须这样做,我只是读了足够多的书,担心它在以后的某个阶段不起作用。
InvokeDelegate 实际上是在另一个文件中声明的,但是我真的需要一个专门用于此目的的整个委托(delegate)吗?根本就没有通用委托(delegate)吗?
我的意思是,例如,有一个 Pen 类,但也有 Pens。pen-of-choice 所以您不必重新制作整个东西。这不一样,但我希望你明白我的意思。

最佳答案

是的。在 .NET 3.5 中,您可以使用 FuncAction委托(delegate)们。 Func 委托(delegate)返回一个值,而 Action 委托(delegate)返回 void。类型名称如下所示:

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 个参数,但这对我来说已经足够了。

关于c# - C# 中的匿名委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/978063/

相关文章:

c# - 合并词典的噩梦

c# - 测试表是否至少有特定的存储过程,否则测试失败 c#

ios - 我的 iOS 委托(delegate)方法是否应该始终在主线程上返回?

ios - 为什么MKMapView的mapView是:viewForOverlay: not called when userlocation is enabled?

c# - 使用运行时已知的类型创建委托(delegate)

c# - 销毁对象时自定义事件是否需要设置为null?

c# - 行号不正确的堆栈跟踪

javascript - 我怎样才能把这个匿名函数变成一个命名函数,这样我就可以把它移到一个外部 JS 文件中以便重用

java - 如何实现比较器来比较名称?

c# - 使用匿名方法是否有任何开销?