• C#委托类型


    定义

    表示委托,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法。 Delegate 类是委托类型的基类。然而,只有系统和编译器可以显式地从 Delegate 类或 MulticastDelegate 类派生。此外,还不允许从委托类型派生新类型。Delegate 类不是委托类型,该类用于派生委托类型。

    问题

    该类型不支持 直接使用 deleagte 关键字赋值实例

    如下

    this.Invoke(delegate
                    {
                        this.textBox1.Text = num.ToString();
                    });

    上述代码 为winform中窗体类的成员方法, 其不能通过编译 , 无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型

    Google结果

    The problem the user is seeing is that the Thread ctor accepts a specific delegate – the ThreadStart delegate. The C# compiler will check and make sure your anonymous method matches the signature of the ThreadStart delegate and, if so, produces the proper code under-the-covers to create the ThreadStart delegate for you.

    But Control.Invoke is typed as accepting a “Delegate”. This means it can accept any delegate-derived type. The example above shows an anonymous method that has a void return type and takes no parameters. It’s possible to have a number of delegate-derived types that match that signature (such as MethodInvoker and ThreadStart – just as an example). Which specific delegate should the C# compiler use? There’s no way for it to infer the exact delegate type so the compiler complains with an error.

    对于Thread.ctor()来说,由于接受的是一个ThreadStart委托,编译器便可以将匿名函数与ThreadStart委托类型匹配,最后能够正确编译。
    而对于Control.Invoke()来说,任何的代理类型都是可接受的,也就是说ThreadStart和MethodInvoker都是可以接受的类型。这样编译器反而不知道应该用哪个代理去匹配匿名函数了,导致了编译错误的发生。

    引用自http://www.cnblogs.com/yelaiju/archive/2010/09/16/1827691.html

    解决方案

    Invoke(new MethodInvoker(delegate { this.textBox1.Text = num.ToString();}));
    Invoke(new MethodInvoker(() => { this.textBox1.Text = num.ToString();});
    
    this.Invoke((ThreadStart)delegate
                    {
                         this.textBox1.Text = num.ToString();
                    });
  • 相关阅读:
    对《分享一下自己用c++写的小地图》一文的补充
    大神的Blog挂了,从Bing快照里复制过来的备份
    如何创建独立的UE4服务端
    打包如何打包额外文件,比如Sqlite数据库的db文件
    关于如何通过定义自己的CameraManager来控制视角
    Slate中绑定动态数据
    分享一下自己用c++写的小地图
    2016.8看到的一些有用的文章
    如何在插件中添加Actor类
    如何使用的Ue4自带的SQLiteSupport
  • 原文地址:https://www.cnblogs.com/wycm/p/5338906.html
Copyright © 2020-2023  润新知