標籤:style blog http color io os ar 使用 sp
C#委託起源
最近參加實習和奔走於各大招聘會,被問及很多技術方面的問題,C#問的較多的就是委託和linq。linq之前已經寫過一篇文章,可以參見
http://blog.csdn.net/yzysj123/article/details/38778371。
這裡講講C#為什麼用委託和什麼是委託。學習過C++的都知道,C++的指標非常的靈活好用,但又給編程人員帶來了很多頭痛,如野指標問題等。而C#就遺棄了指標,但相應的功能通過了其他方式來實習,如C++中指標變數、引用,C#裡面可以通過ref,out等實現。C++中的指標函數,C#則可以通過委託來實現,具體看如下例子。
#include <string.h> #include <stdio.h> int funcA(int a,int b); int funcB(int a,int b); int main(int argc, char *argv[]) { int (*func)(int,int); func = funcA; printf("%d\n",func(10,1)); func = funcB; printf("%d\n",func(10,1)); } int funcA(int a,int b) { return a + b; } int funcB(int a,int b) { return a - b;} 以上就是通過C++一個指標函數可以調用其他相同參數類型的多個函數。而C#中委託的功能,也可以看作是對C++這種功能的實現。具體代碼如下:
<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 21.59375px; white-space: pre-wrap;">// 節選自《</span><span style="color: rgb(0, 130, 0); font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; line-height: 21.59375px; white-space: pre-wrap;">C#入門經典》</span>
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace weituo{ class Program { static void Main(string[] args) { // 聲明委託變數 ProcessDelegate process; Console.WriteLine("請輸入用逗號分隔的兩個數字:"); string input = Console.ReadLine(); int commaPos = input.IndexOf(','); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1,input.Length - commaPos -1)); Console.WriteLine("輸入M乘法D除法</a>"); input =Console.ReadLine(); // 初始化委託變數 if(input =="M") process = new ProcessDelegate(Multiply); //注釋:此處也可以寫process = Multiply else process = new ProcessDelegate(Divide); // 使用委託調用函數 double result = process(param1,param2); Console.WriteLine("結果:{0}",result); Console.ReadKey(); } // 聲明委託 delegate double ProcessDelegate(double param1,double param2); static double Multiply(double param1, double param2) { return param1 * param2; } static double Divide(double param1, double param2) { return param1 / param2; } }}
C#委託之愚見