
c sharp初学者
举个简单的吧。
static string displayString = "jude law";
static void Main (string[] args)
{
Timer myTime = new Timer(1000);
myTimer.Elapsed += new ElapsedEventHander(eventFun); //订阅事件
myTimer.Start();
Console.ReadKey();
}
...
static void eventFun(object source, ElapsedEventArgs e) //事件处理函数的签名必须与委托参数一致
{
Console.Write(displsyString);
}
自己声明委托并订阅事件:
using System;
namespace MyProject
{
public delegate void Call(); // 声明委托
class myClass
{
public event Call show; // 声明事件
public void myEvent()
{
show(); // 引发事件
}
public static void display()
{
Console.WriteLine("Hello World");
}
static void Main(string[] args)
{
myClass obj = new myClass();
obj.show += new Call(display); // 订阅事件
obj.myEvent();
}
}
}
需要注意的是事件一定基于某个委托,而委托会注册一个方法,当引发这个事件时会自动调用此方法