C 內建泛型委託 Func委託

2021-09-28 15:21:10 字數 2207 閱讀 5826

func委託代表有返回型別的委託

檢視func的定義:

using system.runtime.compilerservices;

namespace system

你會發現,func其實就是有多個輸出引數並且有返回值的delegate。

func至少0個輸入引數,至多16個輸入引數,根據返回值泛型返回。必須有返回值,不可void。

func表示沒有輸入參參,返回值為int型別的委託。

func表示傳入引數為object, string ,返回值為int型別的委託。

func表示傳入引數為object, string, 返回值為int型別的委託。

func表示傳入引數為t1,t2,,t3(泛型),返回值為int型別的委託。

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading.tasks;

namespace fundemo

; int result2 = fun2();

console.writeline(result2);

console.writeline("----------------------------");

funcfun3 = () => ;

int result3 = fun3();

console.writeline(result3);

console.writeline("----------------------------");

//有乙個引數,乙個返回值

funcfun4 = new func(funwithpara);

int result4 = fun4(4);

console.writeline($"這裡是乙個引數乙個返回值的方法,返回值是:");

console.writeline("----------------------------");

// 使用委託

funcfun5 = delegate (int i) ;

string result5 = fun5(5);

console.writeline($"這裡是乙個引數乙個返回值的委託,返回值是:");

console.writeline("----------------------------");

// 使用匿名委託

funcfun6 = (int i) =>

;string result6 = fun6(6);

console.writeline($"這裡是乙個引數乙個返回值的匿名委託,返回值是:");

console.writeline("----------------------------");

// 多個輸入引數

funcfun7 = new func(funwithmultipara);

bool result7 = fun7(2, "2");

console.writeline($"這裡是有多個輸入引數的方法,返回值是:");

console.writeline("----------------------------");

// 使用委託

funcfun8 = delegate (int i, string s)

;bool result8 = fun8(2, "abc");

console.writeline($"這裡是有多個輸入引數的委託,返回值是:");

console.writeline("----------------------------");

// 使用匿名委託

funcfun9 = (int i, string s) =>

;bool result9 = fun9(45, "ert");

console.writeline($"這裡是有多個輸入引數的匿名委託,返回值是:");

console.readkey();

}static int funwithnopara()

static int funwithpara(int i)

static bool funwithmultipara(int i,string s)

}}

Func泛型委託

描述 封裝乙個具有乙個引數並返回tresult引數指定的型別值的方法.語法 public delegate tresult func t arg 引數型別 t 此委託封裝的方法的引數型別.tresult 此委託封裝的方法的返回值型別.引數 arg 委託封裝的方法的引數 返回值 此委託封裝的方法的返回...

委託, 泛型委託,Func和Action

使用委託來做一些事情,大致思路是 1 定義宣告乙個委託,規定輸入引數和輸出型別。2 寫幾個符合委託定義的方法。3 把方法列表賦值給委託 4 執行委託 internal delegate int mydelegate class programconsole.readkey static ienume...

Action和Func泛型委託

1.泛型action委託表示引用乙個void返回型別的方法。因為這個委託類存在不同的變體,所以可 以傳遞至多16種不同的引數型別。沒有泛型引數的action類可呼叫沒有引數的方法。action 呼叫帶乙個引數的方法,action呼叫帶兩個引數的方法,action呼叫帶8個引數的方法。2,func委託...