【问题标题】:I am having an error in the below code for event delegation model我在下面的事件委托模型代码中遇到错误
【发布时间】:2017-02-22 10:47:37
【问题描述】:

我创建了一个表单和两个 .cs 文件。

第一个文件form1.cs:

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private Class1 _enemy;

    private void button1_Click(object sender, EventArgs e)
    {
        _enemy = new Class1(this);
        _enemy.LoopInteration += OnLoopInteration;
        _enemy.MyMethod();
        _enemy.LoopInteration -= OnLoopInteration;
    }
    private void OnLoopInteration(object sender, LoopCounterArgs e)
    {
        textBox1.Text = Convert.ToString(e.Iteration);
    }
}
}

第二个文件class1.cs:

namespace WindowsFormsApplication4
{
public class LoopCounterArgs : EventArgs
{
    public int Iteration { get; set; }

    public LoopCounterArgs(int iteration)
    {
        Iteration = iteration;
    }
}
public class Class1
{
    public event EventHandler<LoopCounterArgs> LoopInteration;
    public Class1(Form1 form)
    {
        _form1 = form;
    }
    public void MyMethod()
    {
        for (int j = 1; j <= 20; j++)
        {
            LoopInteration?.Invoke(this, new LoopCounterArgs(j));
            //Thread.Sleep(100);
        }
    }
    private Form1 _form1;
}

}

和form1的表单设计:

Form1 Design

现在出现以下错误:

*错误1:

无效的表达式术语“。” c:\users\43060\documents\visual studio 2013\Projects\WindowsFormsApplication4\WindowsFormsApplication4\Class1.cs 29 32 WindowsFormsApplication4

错误2:

语法错误,':' 应为 c:\users\43060\documents\visual studio 2013\Projects\WindowsFormsApplication4\WindowsFormsApplication4\Class1.cs 29 33 WindowsFormsApplication4*

我想要的是,当用户单击 form1 上的按钮时,for 循环在 class1.cs 中运行,结果显示在 form1 文本框中。 严格要使用事件+委托模型。

【问题讨论】:

  • 不清楚为什么您的Class1 在不使用表单时引用了表单 - 但您也没有向我们展示哪一行有问题。鉴于您尚未提供 using 指令,我们无法将错误消息中的行号映射到源代码中的行...
  • 但除此之外,您的class1.cs 为我编译,表明还有其他问题。您实际上在使用 Visual Studio 2013 吗?如果是这样,您不能使用空条件运算符...我建议升级到 VS2015。
  • @JonSkeet 在这一行给出错误 LoopInteration?.Invoke(this, new LoopCounterArgs(j));说语法错误。我正在使用 VS 2012
  • 对,所以您使用的是 C# 5 编译器。您不能在 VS2012 中使用 C# 6 功能。
  • 我已经说过:使用 C# 6 编译器(例如通过使用 VS2015)...或者停止尝试使用 C# 6 功能。

标签: c# .net winforms visual-studio-2012


【解决方案1】:

应该是这样去掉"?"

LoopInteration.Invoke(this, new LoopCounterArgs(j));

【讨论】:

  • 如果没有订阅该事件,则会抛出异常。 OP 要么需要明确处理,要么更新到 C# 6 编译器,以便他们可以使用 C# 6 功能。
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 2012-05-30
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多