最近手頭的活,乾的比較快,天天都有時間學習,這幾天一直在看委託,作個總結,之後要是模糊了,看看能記起來,沒搞懂使用委託的情景。函數
委託能夠自定義,也可使用內置委託學習
自定義委託:delegate T4 AllDeleate<in T1, in T2, in T3, out T4>(T1 a, T2 b, T3 c);//是根據查看源碼摸你寫的委託源碼
無返回值委託: string
Action<string> action = (a) =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(a + i);
}
};it
有返回值委託:Func<string, string> func = (a) => a + "你好";io
只有一個參數返回布爾類型委託:class
Predicate<int> pre = (d) =>
{
int tag = 10;
bool bo = d > tag ? true : false;
return bo;
};匿名函數
//根據源碼編寫委託foreach
var dele = new AllDeleate<string, string, string, string>(TestDeleage);
var str = dele("我是a", "我是b", "我是c");
Console.WriteLine(str);List
public string TestDeleage(string a, string b, string c)
{
return "根據源碼編寫委託,並輸出a:" + a + ",b:" + b + ",c:" + c;
}
//內置委託,並遍歷委託輸出
Func<string, string> func = GetName;//聲明委託並註冊
func += (d) => d + "我是匿名委託";//註冊
var deleteArray = func.GetInvocationList();//多路廣播委託調用列表
foreach (Func<string, string> item in deleteArray)
{
var mag = item("小李");
Console.WriteLine(mag);
}
private string GetName(string name)
{
Console.WriteLine("委託調用方法");
return name + "你好,歡迎使用委託";
}
//predicate委託
Predicate<int> pre = (d) =>
{
int tag = 10;
bool bo = d > tag ? true : false;
return bo;
};
Console.WriteLine("predicate委託匿名函數:" + pre(10));
Predicate<int> preTest = GetBool;
Console.WriteLine("predicate委託函數:" + GetBool(12));
private static bool GetBool(int num)
{
int tag = 10;
bool bo = num > tag ? true : false;
return bo;
}
//編寫委託
var nums = TsetReturn("小明", GetName);
Console.WriteLine(nums);
public static T2 TsetReturn<T1, T2>(T1 t, Func<T1, T2> func)
{
Console.WriteLine("進入方法");
T2 num = func(t);
return num;
}
private static string GetName(string name)
{
Console.WriteLine("委託調用方法");
return name + "你好,歡迎使用委託";
}
//委託實際應用
public static void DiaoYongTest()
{
DelteateClass delteateClass = new DelteateClass();
delteateClass.td = new TestDeleate(delegate (int i, int maxValue)
{
Console.WriteLine("當前進度:" + i);
Console.WriteLine("最大值:" + maxValue);
});
delteateClass.td += new TestDeleate((a, b) =>
{
Console.WriteLine("Lambda當前進度:" + a);
Console.WriteLine("Lambda最大值:" + b);
});
delteateClass.td += new TestDeleate(GetProgress);
delteateClass.ApplyTest();
}
private static void GetProgress(int i, int maxValue)
{
Console.WriteLine("GetProgress當前進度:" + i);
Console.WriteLine("GetProgress最大值:" + maxValue);
}
class DelteateClass { public TestDeleate td; public void ApplyTest() { int maxValue = 10; var list = td.GetInvocationList(); foreach (var item in list) { for (int i = 0; i < maxValue; i++) { item?.DynamicInvoke(i, maxValue); } } } }