using System;
namespace ConsoleApp_CSXP
{
class 小弟
{
//1.聲明事件委託
public delegate void 被人扁(object sender, EventArgs e);
//2.聲明事件實例
public event 被人扁 挨扁;
//3.包含事件
private void 挨扁了(EventArgs e)
{
if(this.挨扁 != null)
this.挨扁(this, e);
}
//4.觸發事件
public void 被扁()
{
Console.WriteLine("被扁ing...");
this.挨扁了(EventArgs.Empty);
}
}
class 我
{
private 小弟 我小弟 = null;
public 我(小弟 小小弟)
{
this.我小弟 = 小小弟;
//註冊事件
this.我小弟.挨扁 += new 小弟.被人扁(this.担心);
}
public void 担心(object sender, EventArgs e)
{
Console.WriteLine("我担心");
}
}
}
此博客展示了 C# 代码中事件委托和事件触发的实现。定义了一个包含事件委托和事件实例的类,通过方法触发事件。还定义了另一个类,在构造函数中注册事件,并在事件触发时执行相应操作,体现了 C# 事件机制的运用。

1907

被折叠的 条评论
为什么被折叠?



