今天在看Unity的NGUI代码时,发现许多delegate,然后又去查C#资料,发现了event和delegate,写了一些代码,明白了不少..
//第一个
class A
{
public delegate void d_Test(int a, int b);
public event d_Test myEvents;
public void run()
{
if (Console.ReadLine() == "a")
{
myEvents(1, 2); //产生事件
}
}
}
class M
{
public static void Main()
{
A a = new A();
M m = new M();
a.myEvents += new A.d_Test(m.Func);
a.run();
}
public void Func(int a, int b)
{
Console.WriteLine(a + b);
}
}________________________________________________________________________________________________________________________________
public class App
{
public App() { }
public delegate void dele_func(MyArgs args, int b);
public event dele_func event_func;
public void call()
{
MyArgs args = new MyArgs("Lee");
event_func(args, 2);
}
}
public class MyArgs : EventArgs
{
public MyArgs(string sname) { name = sname; }
public string name { get; set; }
}
public class handleApp
{
public handleApp() { }
public void myName(MyArgs args, int b)
{
Console.WriteLine(args.name);
}
}
class My_Main
{
public static void Main()
{
App app = new App();
handleApp h_app = new handleApp();
app.event_func += new App.dele_func(h_app.myName);
if (Console.ReadLine() == "a")
{
app.call();
}
Console.Read();
}
}