1:委託是一種數據類型,和類一樣。委託是對方法的抽象。把方法當做變量來處理,其作用就是指向一個方法。委託也相當於實現多態,函數可以接受參數,而這裏使得參數更加靈活化。相當於c++中函數指針。
namespace 委託
{
//define delegate
public delegate void DelegateAdd(int a,int b);
}
namespace 委託
{
class Program
{
static void add1(int a, int b)
{
Console.WriteLine("1");
}
static void add2(int a,int b)
{
Console.WriteLine("2");
}
static void Main(string[] args)
{
//Define a delegate var,because the fuction of "add1" be similar as the define of delegate,
//so we can use it as the function's parameters
DelegateAdd delegate1 = new DelegateAdd(add1);
//DelegateAdd delegate1 = add1;也可以直接這樣定義
delegate1 += add2;//Invoking the add1 and add2 together
delegate1(1, 5);//Be similar as “add1(1,5)”
Console.ReadKey();
}
}
}
傳遞的函數的參數的簽名,要和定義的委託參數簽名一致。
2:委託事件:對應於客觀世界就是錢包,銀行可以往你的卡里打錢,或者扣款,但不能使用你的錢包進行購物,只有你自己纔可以。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委託事件
{
public class Dog
{
//事件,其本質就是委託對象,調用執行只能在內部完成=Nature of event is a delegate, when we using it to do something,it must be performed internally.
//也就是一個函數=We can also treat it as a function
//在外部可以使用-= 或者+=
public event Action helloEvent;
public void Sayhello()
{
Console.WriteLine("sd");
helloEvent();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委託事件
{
class Program
{
public static event Action helloEvent2;//非靜態的字段調用要用對象,所以加static
static void Main(string[] args)
{
Dog d1 = new Dog();
//d1.helloEvent()//錯誤,helloEvent事件不能外部直接調用
d1.helloEvent += helloEvent2;//可以使用+=或者-=
d1.Sayhello();// helloEvent();在內部調用是可以的
Console.ReadKey();
}
}
}
但會出現運行時錯誤,
3:委託實例:在方法中通過傳遞不同的方法,對另一個參數實現不同的效果。即大寫,小寫
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委託
{
class Program
{
static string ToUpper(string str)
{
return (str.ToUpper());
}
static string ToLower(string str)
{
return (str.ToLower());
}
static void GoTo(Func<string,string> s1,string str)//s1就相當於一個方法名
{
Console.WriteLine(s1(str));//調用s1函數,需要string參數,並返回string類型的值
}
static void Main(string[] args)
{
GoTo(ToLower, "SWW");
GoTo(ToUpper, "Sopp");
Console.ReadKey();
}
}
}