c#中的泛型委托詳解
今天學習一下c#中的泛型委托。
1.一般的委托,delegate,可以又傳入參數(<=32),聲明的方法為 public delegate void SomethingDelegate(int a);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateSummary {
public delegate void GetIntDelegate(int a); //聲明一個委托
public class getIntClass {
public static void SetDelegateString(int a,GetIntDelegate getIntDelegate) {//使用委托
getIntDelegate(a);
}
public void getInt1(int a) { //方法1
Console.WriteLine("getInt1方法調用,參數為:" + a);
}
public void getInt2(int a) { //方法2
Console.WriteLine("getInt2方法調用,參數為:" + a);
}
}
class Program {
static void Main(string[] args) {
getIntClass gc=new getIntClass();
getIntClass.SetDelegateString(5, gc.getInt1); //方法1,2作為委托的參數
getIntClass.SetDelegateString(10, gc.getInt2);
Console.WriteLine("=====================");
GetIntDelegate getIntDelegate;
getIntDelegate = gc.getInt1; //將方法1,2綁定到委托
getIntDelegate += gc.getInt2;
getIntClass.SetDelegateString(100, getIntDelegate);
Console.Read();
}
}
}
輸出結果,注意兩種方式的不同,第一種將方法作為委托的參數,第二種是將方法綁定到委托。

2.泛型委托之Action,最多傳入16個參數,無返回值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateSummary {
class Program {
static void Main(string[] args) {
TestAction<string>(getString, "WhiteTaken"); //傳入方法
TestAction<int>(getInt, 666);
TestAction<int, string>(getStringAndInt, 666, "WhiteTaken");
Console.Read();
}
public static void TestAction<T>(Action<T> action,T p1) { //Action傳入一個參數測試
action(p1);
}
public static void TestAction<T, P>(Action<T, P> action, T p1, P p2) { //Action傳入兩個參數測試
action(p1,p2);
}
public static void getString(string a) { //實現int類型打印
Console.WriteLine("測試Action,傳入string,并且傳入的參數為:" +a);
}
public static void getInt(int a) { //實現String類型打印
Console.WriteLine("測試Action,傳入int,并且傳入的參數為:" + a);
}
public static void getStringAndInt(int a, string name) { //實現int+string類型打印
Console.WriteLine("測試Action,傳入兩參數,并且傳入的參數為:" + a+":"+name);
}
}
}
測試結果:

3.泛型委托之Func,最多傳入16個參數,有返回值。(寫法與Action類似,只是多了返回值)
4.泛型委托之predicate(不是很常用),返回值為bool,用在Array和list中搜索元素。(沒有用到過,等用到了再更新)
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
C#12中的Primary?Constructors主構造函數詳解
主構造函數把參數添加到class與record的類聲明中就是主構造函數,這篇文章主要介紹了C#12中的Primary?Constructors 主構造函數,需要的朋友可以參考下2023-11-11
C#中的Task.Delay()和Thread.Sleep()區(qū)別(代碼案例)
Task.Delay(),async/await和CancellationTokenSource組合起來使用可以實現可控制的異步延遲。本文通過多種代碼案例給大家分析C#中的Task.Delay()和Thread.Sleep()知識,感興趣的朋友一起看看吧2021-06-06
C#中static void Main(string[] args) 參數示例詳解
這篇文章主要介紹了C#中static void Main(string[] args) 參數詳解,本文通過具體示例給大家介紹的非常詳細,需要的朋友可以參考下2017-03-03

