代理是一種特殊的,指向某個方法模塊所在的地址。一般來講,那個方法模塊,可以是一個普通的方法,更多的時候,是一團匿名的lamda表達式,即一個匿名方法。現在簡單理解一下代理的簡寫方式,即Action關鍵字。
class A
{
B b = new B();
public delegate string Show(string result);
public string Execute()
{
Show s = new Show(b.MyShow);
string str = s.Invoke("ttt");
return str;
}
}
class B
{
public string MyShow(string s)
{
return s + ">>>>>>>>>";
}
}
static void Main(string[] args)
{
A a = new A();
a.Execute();
}這樣,使用A的時候,只改變B中MyShow的代碼,就能定制A中Execute的執行結果。具有同樣功能的代碼,我們用Action類型來完成。 class C
{
D d = new D();
Action action;
public void Execute()
{
action = d.MyShow2;
action.Invoke("ttt");
}
}
class D
{
public void MyShow2(string s)
{
Console.WriteLine(s + ">>>>>>>>>");
}
}
static void Main(string[] args)
{
A a = new A();
a.Execute();
}