基於C#委託的深入分析

來源:互聯網
上載者:User

1.委託的定義

委託可以看成是一種資料類型,可以用於定義變數能接受的值只能是一個方法。

委託簡單的樣本:

複製代碼 代碼如下:namespace DelegateDemo
{
class Program
{
public delegate int MathOptDelegate(int value1,int value2);
public int add(int value1, int value2)
{
return value1 + value2;
}

static void Main(string[] args)
{
MathOptDelegate mod;
Program p = new Program();
mod =p.add;
Console.WriteLine(mod(3,5));
Console.ReadKey();
}
}
}

利用委託的建構函式建立委託
複製代碼 代碼如下:namespace DelegateDemo
{
class Program
{
public delegate int MathOptDelegate(int value1,int value2);
public int add(int value1, int value2)
{
return value1 + value2;
}

static void Main(string[] args)
{

Program p = new Program();
MathOptDelegate mod = new MathOptDelegate(p.add);
Console.WriteLine(mod(3,5));
Console.ReadKey();
}
}
}

從這個樣本中可以得出這樣的直觀印象:

委託可以堪稱是一個方法的容器,將某一個具體的方法裝入後,就可以把它當成方法一樣使用。

2.委託的調用列表

從上一個例子看,委託變數可以引用某一個方法,調用它就相當於調用這個方法。

如果委託今年僅是方法調用的另一種形式,那何必多此一舉引入委託這一特性?直接調用方法不是更簡單明了?

因為委託變數不僅可以引用另一個方法,還可以組合多的方法並批量執行它們。

複製代碼 代碼如下:namespace DelegateDemo2
{
class Program
{
public delegate void MyDelegate(String str);
public static void hello(String str)
{
Console.WriteLine(str+"你好");
}
public static void goodbye(String str)
{
Console.WriteLine(str+"再見");
}
static void Main(string[] args)
{
MyDelegate a,b,c,d;
a = Program.hello;
a("a");
b = Program.goodbye;
b("b");
c = a + b;//等價將兩個方法體合并
c("c");// c你好 c再見
d = c - a;
d("d");//d再見
Console.ReadKey();

}
}
}

像C這樣的委託變數可稱為多路委託變數。

可以用加法運算子來組合單個委託變數為多路委託變數。類似的,也可以使用減法運算子來從一個多路委託變數中移除某個委託變數。

複製代碼 代碼如下:namespace DelegateDemo2
{
class Program
{
public delegate void MyDelegate(String str);
public static void hello(String str)
{
Console.WriteLine(str+"你好");
}
public static void goodbye(String str)
{
Console.WriteLine(str+"再見");
}
static void Main(string[] args)
{
MyDelegate a,b,c,d;
a = Program.hello;
a("a");
b = Program.goodbye;
b("b");
c = a + b;//等價將兩個方法體合并
c("c");// c你好 c再見
d = c - a;
d("d");//d再見
Delegate[] ds;
ds = c.GetInvocationList();
foreach(Delegate s in ds)
{
Console.WriteLine(s);
//DelegateDemo2.Program+MyDelegate
//DelegateDemo2.Program+MyDelegate
}
Console.WriteLine(ds.Length);
Console.ReadKey();

}
}
}

如果委託定義的方法有傳回值,則多路委託變數的傳回值為委託調用列表中最後一個方法的傳回值,中間調用的方法傳回值會被丟棄。

使用泛型委派:

Func系列委託

以下是Func熄了委託的定義,依其泛型型別參數的多少有多個重載形式:

public delegate TResult Func<Tresult>();

public delegate TResult Func<T,Tresult>();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.