zoukankan      html  css  js  c++  java
  • 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#路径中获取文件全路径、目录、扩展名、文件名称
    c#FTP应用---windows iis
    c#FTP应用---FileZilla Server
    在VS2010中使用Git管理源代码
    ABB机器人---PCSDK简介
    几款软件需求分析工具
    快速排序
    springmvc和struts2的区别比较
    Struts中ActionContext和ServletActionContext的比较
    设计模式--适配器模式
  • 原文地址:https://www.cnblogs.com/wycm/p/5338906.html
Copyright © 2011-2022 走看看