0

在阅读有关事件的在线教程后,我想我几乎知道发生了什么。我开发了以下非常简单的代码来在值大于 5 的情况下触发事件。我知道代码非常无用,但我正在使用它来表达我的观点。(而不是主我只是使用按钮事件来触发代码。)

//declare the delegate
public delegate void MyDelegate(string str);

public class SomeClass
{
    public event MyDelegate MyEventFromDelegate;
    private int i;
    public int I
    {
            get
            { return i; }
            set
            {
                if (value > 5)
                {
                    MyEventFromDelegate("Value Greater than 5");
                    i = 0;
                }
                else
                {
                    i = value;
                }
            }
    }

}

public partial class Form1 : Form
{
    public Form1()
    { InitializeComponent();  }

    public void Method_To_Call(String rx)
    {   MessageBox.Show("This method will be called if greater than 5");}

    private void button1_Click(object sender, EventArgs e)
    {
        SomeClass a = new SomeClass();
        a.MyEventFromDelegate +=new MyDelegate(Method_To_Call);
        a.I = 12;
    }
}

我在这里唯一担心的是当我们想用声明引发事件时

MyEventFromDelegate("Value Greater than 5");

如果稍后(在按钮单击事件中)我们实际上要为它分配一个函数,以便在每次触发事件时调用,那么将参数传递给事件的关键是此时。

4

1 回答 1

1

在您非常简单的示例中-没有意义,因为 SomeClass 实例“a”的寿命很短,并且因为您没有使用传递给 Method_To_Call 的 rx 参数。

您的表单方法 button1_Click 通过委托连接到按钮的 Click 事件。Button 不知道点击它时会执行什么代码。它所要做的就是发出被点击的信号。该信号是使用委托实现的。

您可以将您的委托定义为具有传递检查值的整数参数。然后,虽然只有当值大于 5 时才会调用事件方法,但在事件方法内部,您可以根据实际值做不同的事情。

//declare the delegate
public delegate void MyDelegate(int aValue);

public class SomeClass
{
    public event MyDelegate MyEventFromDelegate;
    private int i;
    public int I
    {
            get
            { return i; }
            set
            {
                if (value > 5)
                {
                    MyEventFromDelegate(value);
                    i = 0;
                }
                else
                {
                    i = value;
                }
            }
    }

}

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();  
    }

    public void Method_To_Call(int aValue)
    {   
      MessageBox.Show("This method signals that value is greater than 5. Value=" + aValue.ToString());
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SomeClass a = new SomeClass();
        a.MyEventFromDelegate +=new MyDelegate(Method_To_Call);
        a.I = 12;
    }
}
于 2012-11-09T01:49:36.500 回答