日期:2014-05-17  浏览次数:20663 次

C#中event关键字有什么用?
我在程序中定义了一个委托
public delegate void yin(int s);
public event yin tuto;
另外一段代码给tuto赋值后, 运行函数tuto(5);

这个event不要好像也可以,要和不要有什么区别呢?

------解决方案--------------------
delegate 委托
event 事件
事件是特殊的委托,是多播委托,可以添加多个事件处理函数,但是委托只能绑定一个处理函数。
------解决方案--------------------
引用:
public delegate void yin(int s);
public event yin tuto;//有event定义
另外一段代码给tuto赋值后, 运行函数tuto(5);

public delegate void yin(int s);
public yin tuto;//没有event定义
另外一段代码给tuto赋值后, 运行函数tuto(5);

运行没什……

5楼说的就是你想要的答案,可惜你看不懂...
------解决方案--------------------
你可以往事件上绑定多个处理函数,使用+=运算符,比如
button.Click += button1_Click1;
button.Click += button1_Click2;
这样,多个处理函数都可以被调用。
幕后,event的+=运算会被编译器转化成多播委托的合并操作(Delegate.Combine方法的调用,而你却不用操心这些)
------解决方案--------------------
给个事件的例子

using System.Windows.Forms;

namespace 窗体间通信
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Form2 f2=new Form2();

            f2.send += delegate(string text)
            {//订阅f2的事件send,并以匿名方法处理
                textBoxForm1.Text = text;
            };
            f2.Show();
        }
    }
}


using System;