c#事件学习总
结(2009-05-11 18:35:50)
标签:it
刚刚学了事件的编程,c#中事件的编写对于刚学习的人来说的确不是很容易理解,我自己也刚学,自己总结了一下几个步骤,一些术语什么的可能不是很专业,但是希望对和我一
样刚学的it人有所帮助。。。
namespace TestEvent
{
//first: declare a delegate for the event to use 第一步:声明一个委托变量
public delegate void ChangeDelegate(object obj,string name);
class Program
{
//second: declare a event 第二步:声明定义一个事件
event ChangeDelegate NameChange;
private string _name;
public string Name
{
// get { return _name; }
set
{
_name = value;
//fifths: use the event and active the event第五步:在适当的地方添加事件响应事件
NameChange(this, _name);
}
}
//third: declare a methord to used for active for the event action 第三步:声明定义一个事件响应方法注意返回值以及参数
public void ChangeName(object obj,string name)
{
Console.WriteLine("hello");
}
public Program()
{
//forth:add the methord to the event delegate 第四步:把响应方法添加到事件委托当中
NameChange += new ChangeDelegate(ChangeName);
}
static void Main(string[] args)
{
Program p = new Program();
p.Name = "hhh";
}
}
}