我在下面的事件委托模型代码中出错

时间:2017-02-22 10:47:38

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

我创建了一个表单和两个.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:

  

无效的表达术语&#39;。&#39; c:\ users \ 43060 \ documents \ visual studio   2013 \ Projects \ WindowsFormsApplication4 \ WindowsFormsApplication4 \ Class1.cs 29 32 WindowsFormsApplication4

错误2:

  

语法错误,&#39;:&#39;预计c:\ users \ 43060 \ documents \ visual studio   2013 \ Projects \ WindowsFormsApplication4 \ WindowsFormsApplication4 \ Class1.cs 29 33 WindowsFormsApplication4 *

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

1 个答案:

答案 0 :(得分:0)

应该是删除“?”

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