C#委託的幾種表現方式
以Func為例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mytest.del
{
class Program
{
static Func<int, int, int> plusDel;
static void Main(string[] args)
{
plusDel = delegate(int a, int b)
{
return a + b;
};
int sum1 = plusDel(1, 1);
plusDel = (a, b) =>
{
return a + b;
};
int sum2 = plusDel(1, 1);
plusDel = new Func<int, int, int>((a, b) =>
{
return a + b;
});
int sum3 = plusDel(1, 1);
plusDel = new Func<int, int, int>(GetResult);
int sum4 = plusDel(1, 1);
Console.WriteLine(string.Format("sum1={0},sum2={1},sum3={2},sum4={3}", sum1, sum2, sum3, sum4));
Console.ReadKey();
}
private static int GetResult(int a, int b)
{
return a + b;
}
}
}
這裡的sum1,sum2,sum3,sum4都是為2的。
現在我們自己定義一個委託:
class Program
{
delegate int PlusDel(int a, int b);
static void Main(string[] args)
{
PlusDel del1= GetResult;
PlusDel del2 = new PlusDel(GetResult);
PlusDel del3 = (a, b) => { return a + b; };
int sum1 = del1(1, 1);
int sum2 = del2(1, 1);
int sum3 = del3(1, 1);
}
private static int GetResult(int a, int b)
{
return a + b;
}
}
這裡的sum1,sum2,sum3的計算結果也會是一樣的。
對於引數宣告成delegate的類,可以如下進行操作:
Thread thread1 = new Thread(() => { });
Thread thread2 = new Thread(new ThreadStart(() => { }));
Thread thread3 = new Thread(new ThreadStart(delegate { }));
Thread thread4 = new Thread(new ThreadStart(Method));
private void Method()
{
}
這4個執行緒的效果可以一樣。因為ThreadStart是delegate宣告的。
但是對於Delegate宣告的引數,如下程式碼:
this.BeginInvoke(new Action<int, int>((a, b) =>
{
}), new object[] { 1, 1 });
必須使用new關鍵字進行例項化委託物件。BeginInvoke的原型是如下的:
public IAsyncResult BeginInvoke(Delegate method, params object[] args);
錯誤或者不足的地方,歡迎大家指正。
相關文章
- c#委託C#
- C#自學(一)委託(delegate)、委託泛型、多播委託C#泛型
- 關於C#委託三種呼叫的分享C#
- C#的委託案例C#
- C#中的委託C#
- C# 事件委託C#事件
- C#委託(delegate)C#
- C# 委託事件C#事件
- C#委託與事件C#事件
- C#委託理解(1)C#
- c# 委託測試C#
- C#再識委託C#
- C# 事件 vs 委託C#事件
- C# - 委託與事件C#事件
- C# 委託(delegate)、泛型委託和Lambda表示式C#泛型
- C#反射的委託建立器C#反射
- C# 中的委託和事件C#事件
- C#委託的非同步呼叫C#非同步
- 瞭解下C# 委託(Delegate)C#
- C# 之委託與事件C#事件
- 什麼是委託(C#)C#
- PHP實現BitMEX API POST方式委託掛單PHPAPI
- C#中的委託和事件(續)C#事件
- winform實現委託ORM
- C#基礎:泛型委託C#泛型
- C#基礎委託回顧C#
- C#:委託和自定義事件C#事件
- C#委託使用詳解(Delegates)C#
- C# 委託(Delegates)使用詳解C#
- C#委託回撥的一個例子C#
- 幾種表的連線方式(SQL)SQL
- 用JScript實現VB.Net,C#的[委託Delegate]: (轉)JSC#
- 詳解C#委託和事件(一)C#事件
- 詳解C#委託和事件(二)C#事件
- dotnet 委託的實現解析(2)開放委託和封閉委託 (Open Delegates vs. Closed Delegates)
- 委託、事件--委託例項篇事件
- C#中多執行緒 委託的使用C#執行緒
- 委託、Lambda表示式、事件系列01,委託是什麼,委託的基本用法,委託的Method和Target屬性事件