【问题标题】:Delegate type Cannot convert anonymous method [duplicate]委托类型无法转换匿名方法[重复]
【发布时间】:2013-12-04 07:22:57
【问题描述】:

在下一行“this.dgvReport.Invoke(delegate”中出现错误

“无法将匿名方法转换为类型 'System.Delegate',因为它不是委托类型”

    public void FillProductGrid()
    {
        ProductSP productSP = new ProductSP();
        DataTable dtbl = new DataTable();
        string productname = "";
        dtbl = productSP.StockReport(productname, this.cbxPrint.Checked);
        this.dgvReport.Invoke(delegate
        {
            this.dgvReport.DataSource = dtbl;
        });
    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    只需将转换添加到具有相同签名的某些委托类型:

    this.dgvReport.Invoke((MethodInvoker)(delegate {
            this.dgvReport.DataSource = dtbl;
    }));
    

    【讨论】:

      【解决方案2】:

      Invoke 方法有一个Delegate 类型的参数,您只能将匿名函数转换为特定 委托类型。您要么需要转换表达式,要么(我的首选选项)使用单独的局部变量:

      // Or MethodInvoker, or whatever delegate you want.
      Action action = delegate { this.dgvReport.DataSource = dtbl; };
      dgvReport.Invoke(action);
      

      或者,您可以在 Control 上创建一个扩展方法来特殊情况下的特定委托,这可以使其更简单:

      public static void InvokeAction(this Control control, Action action)
      {
          control.Invoke(action);
      }
      

      然后:

      dgvReport.InvokeAction(delegate { dgvReport.DataSource = dtbl; });
      

      还可以考虑使用 lambda 表达式:

      dgvReport.InvokeAction(() => dgvReport.DataSource = dtbl);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 2010-11-01
        • 2010-12-06
        • 2013-01-30
        • 1970-01-01
        相关资源
        最近更新 更多