關(guān)于C#委托你不可不知的幾件事
作者:楊延成
我們今天要給大家講講C#委托,雖然這屬于基礎(chǔ)知識,但弄清楚了委托究竟是怎么一回事還是有助于大家更好的開發(fā)。
委托是C#中非常重要的一個概念,并在C#中得到了豐富的應(yīng)用,如事件,線程等。那什么是委托呢?具體來說,委托是一種引用方法的類型。一旦為委托分配了方法,委托將與該方法具有完全相同的行為。委托方法的使用可以像其他任何方法一樣,具有參數(shù)和返回值。
委托具有以下特點:
委托類似于 C++ 函數(shù)指針,但它是類型安全的。
委托允許將方法作為參數(shù)進(jìn)行傳遞。
委托可用于定義回調(diào)方法。
委托可以鏈接在一起;例如,可以對一個事件調(diào)用多個方法。
方法不需要與委托簽名精確匹配。有關(guān)更多信息,請參見協(xié)變和逆變。
C# 2.0 版引入了匿名方法的概念,此類方法允許將代碼塊作為參數(shù)傳遞,以代替單獨定義的方法。
在C#中使用委托分為三步:
1.定義委托:
- //聲明委托
- public delegate void MyDel();
2.實例化委托:
- TestDel t = new TestDel();
- Console.WriteLine("-----以下是簡單使用委托演示--------");
- //t.MyMethod();
- ///實例化委托,用一個方法來進(jìn)行實例化
- ///該方法簽名要與委托簽名一致
- MyDel del = new MyDel(t.MyMethod);
3.調(diào)用委托:
- ///調(diào)用委托
- del();
好了,其實委托的變化很復(fù)雜,但基本都會符合這么三個步驟,說過了,這些,再來看一下完整的代碼
- namespace DelegateDemo{
- //聲明委托
- public delegate void MyDel();
- //聲明帶參的委托
- public delegate void MyDel2(int num1, int num2);
- //聲明帶有返值的委托
- public delegate string MyDel3(string s);
- //聲明委托用于演示匿名方法
- public delegate string ProcessString(string s); class Program
- {
- static void Main(string[] args)
- {
- #region 委托演示
- /*
- TestDel t = new TestDel();
- #region 簡單實例化委托與調(diào)用委托
- Console.WriteLine("-----以下是簡單使用委托演示--------
- ");
- //t.MyMethod();
- ///實例化委托,用一個方法來進(jìn)行實例化
- ///該方法簽名要與委托簽名一致
- MyDel del = new MyDel(t.MyMethod);
- ///調(diào)用委托
- del();
- //C#2.0后可以這種方式實例化委托
- MyDel del4 = t.MyMethod;
- del4();
- //用靜態(tài)方法進(jìn)行實例化
- del4 = TestDel.MyStaticMethod;
- del4();
- //以下代碼效果相同
- //MyDel2 del2 = new MyDel2(t.MyMethod);
- //del2(10, 20);
- MyDel2 del2 = t.MyMethod;
- del2(10, 20);
- //MyDel3 del3 = new MyDel3(t.MyMethod);
- //Console.WriteLine(del3("abc"));
- #endregion
- #region 匿名方法實例化委托
- Console.WriteLine("-----以下是匿名方法演示--------");
- //用匿名方法實例化委托
- ProcessString p = delegate(string inputString) {
- return inputString.ToUpper();
- };
- //通過委托調(diào)用匿名方法
- Console.WriteLine(p("aaaa"));
- #endregion
- #region 委托多播演示
- Console.WriteLine("-----以下是委托多播演示--------");
- MyDel mydel1 = t.MyMethod;
- MyDel mydel2 = t.MyMethod2;
- MyDel mydel3 = TestDel.MyMethod3;
- MyDel allMyDel = mydel1 + mydel2 + mydel3;
- allMyDel();
- allMyDel -= mydel3;
- allMyDel();
- #endregion
- #region 委托作為參數(shù)演示
- Console.WriteLine("-------以下是委托作為參數(shù)演示------");
- MyDel3 paramMyDel3 = t.MyMethod;
- TestDel.MyParamMethod("aaa", paramMyDel3);
- #endregion
- #region 委托作為返回值
- Console.WriteLine("---以下是委托作為返回值演示------");
- ///returnMyDel指向t.MyReturnMethod()的返回值
- MyDel3 returnMyDel = t.MyReturnMethod();
- ///returnMyDel指向t.MyMethod
- //MyDel3 returnMyDel = t.MyMethod;
- Console.WriteLine(returnMyDel("sssssssssssss"));
- #endregion
- */
- #endregion
- //MyReturnDelegateTest my = new MyReturnDelegateTest();
- //my.MyTest();
- MyParamDelegateTest myParam = new MyParamDelegateTest();
- myParam.AddBooks();
- myParam.MyTest();
- } } public class TestDel
- {
- #region 普通方法
- public static void MyStaticMethod()
- {
- Console.WriteLine("My Static Method");
- }
- public void MyMethod()
- { Console.WriteLine("MyMethod");
- } public void MyMethod2() {
- Console.WriteLine("My Method 22222222222");
- }
- public static void MyMethod3()
- {
- Console.WriteLine("My Method 3333333333333");
- }
- public void MyMethod(int num1, int num2)
- {
- Console.WriteLine(num1+num2);
- }
- public string MyMethod(string s)
- { return s.ToUpper();
- } #endregion
- /// <summary>
- /// 委托作為方法參數(shù)
- /// </summary>
- /// <param name="s"></param>
- /// <param name="del3"></param>
- public static void MyParamMethod(string s, MyDel3 del3)
- {
- Console.WriteLine(del3(s));
- } /// <summary>
- /// 委托作為返回值
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- public MyDel3 MyReturnMethod()
- {
- ///返回符合委托規(guī)范的方法
- return MyMethod;
- } }
委托作為參數(shù)示例:
委托作為參數(shù)
- public class MyParamDelegateTest
- {
- BookDB bookDB = new BookDB();
- public void AddBooks()
- {
- bookDB.AddBook(new Book() { BookID=1,BookName="C#",Price=123,IsPaperbook=true });
- bookDB.AddBook(new Book() { BookID = 1, BookName = "C#", Price = 123, IsPaperbook = false });
- bookDB.AddBook(new Book() { BookID = 2, BookName = "ASP.Net", Price = 12, IsPaperbook = true });
- bookDB.AddBook(new Book() { BookID = 1, BookName = "ADO", Price = 23, IsPaperbook = false });
- }
- /// <summary>
- /// 用來實例化委托
- /// </summary>
- /// <param name="b"></param>
- public void TestProcessBook(Book b)
- {
- if (b.IsPaperbook) {
- Console.WriteLine(b.BookName);
- } }
- double total = 0;
- public void TotalPrice(Book b)
- { total += b.Price;
- } public void MyTest() {
- //ProcessBook p=TestProcessBook;
- //ProcessBook p1=TotalPrice;
- //ProcessBook p2=p+p1;
- //把方法名做為參數(shù)進(jìn)行傳遞
- bookDB.PrintBook(TestProcessBook);
- bookDB.PrintBook(TotalPrice);
- Console.WriteLine(total);
- } }
- public delegate void ProcessBook(Book b);
- public class BookDB {
- public List<Book> books = new List<Book>();
- public void AddBook(Book b)
- {
- books.Add(b);
- }
- public void PrintBook(ProcessBook process)
- {
- foreach (var book in books) {
- process
- (book); }
- } } public class Book
- { public int BookID { get; set; }
- public string BookName { get; set; }
- public double Price { get; set; }
- public bool IsPaperbook { get; set; }
- }
委托作為返回值:
委托作為返回值
- public delegate int MyReturnDelegate(int num1, int num2);
- public class MyReturnDelegateTest {
- public void MyTest()
- {
- MyCalcuate myCalcuate = new MyCalcuate();
- do
- {
- Console.WriteLine("請輸入符號進(jìn)行以計算( + - * /)");
- string oper = Console.ReadLine();
- Console.WriteLine("請輸入操作數(shù)1");
- string num1 = Console.ReadLine();
- Console.WriteLine("請輸入操作數(shù)2");
- string num2 = Console.ReadLine();
- MyReturnDelegate myReturn = myCalcuate.Calcuate(oper);
- int result = myReturn(int.Parse(num1), int.Parse(num2));
- Console.WriteLine(
- string.Format("{0}{1}{2}={3}", num1,oper,num2, result));
- Console.WriteLine("您還要繼續(xù)嗎?Y/N");
- //string continueFlag = Console.ReadLine();
- //if (continueFlag.ToUpper() == "N") break;
- } while (Console.ReadLine().ToUpper()!="N"); }
- }
- ublic class MyCalcuate
- {
- public MyReturnDelegate Calcuate(string oper) {
- MyReturnDelegate myReturn = null;
- switch (oper)
- { case "+":
- myReturn = delegate(int num1, int num2) { return num1 + num2; };
- break;
- case "-":
- myReturn = delegate(int num1, int num2) { return num1 - num2; };
- break;
- case "*":
- myReturn = delegate(int num1, int num2) { return num1 * num2; };
- break;
- case "/":
- myReturn = delegate(int num1, int num2) { return num1 / num2; };
- break;
- default:
- break; }
- return myReturn;
- } }
原文鏈接:http://www.cnblogs.com/yangyancheng/archive/2011/04/21/2024145.html
責(zé)任編輯:彭凡
來源:
博客園


相關(guān)推薦
2010-05-10 11:08:28





51CTO技術(shù)棧公眾號

業(yè)務(wù)
速覽
速覽
在線客服