您好,登錄后才能下訂單哦!
/* 20160324 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ch06 { class Program { //params 參數數組 static int SumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } //值引用, 1.val is not an const value; 2. val must be initialized static void showDouble(ref int val) { val *= 2; return; } //6.4 struct function 結構函數 struct CustomerName { public string firstName, lastName; public string WriteName() { return firstName + " " + lastName; } } //6.5 函數重載 static int MaxValue(params int[] inArray) { int maxVal = inArray[0]; for (int i = 1; i < inArray.Length; i++) { if (inArray[i] > maxVal) maxVal = inArray[i]; } return maxVal; } static double MaxValue(params double[] inArray) { double maxVal = inArray[0]; for (int i = 1; i < inArray.Length; i++) { if(inArray[i]>maxVal) maxVal = inArray[i]; } return maxVal; } //6.6 delegate 委托 //1.委托的返回值和參數與函數的返回值和參數相同 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; } static void Main(string[] args) { //params 參數數組,并不限定輸入的參數個數 int sum = SumVals(1,5,2,4,5); Console.WriteLine("Summed Values = {0}, ",sum); sum = SumVals(2, 4, 6, 8, 10, 12, 14, 16); Console.WriteLine("Summed Values = {0}.", sum); //Main函數參數,帶參數執行 //右擊項目名稱,選擇屬性,選擇調試,添加命令行參數,運行 foreach(string arg in args) { Console.WriteLine("{0}",arg); } Console.WriteLine("{0} command line argument were specified.", args.Length); //ref 引用類型參數,函數內部改變參數值的方法 Console.WriteLine("Please enter a number."); int enterInt; enterInt = Convert.ToInt32(Console.ReadLine()); showDouble(ref enterInt); Console.WriteLine("double is {0}.", enterInt); //結構函數,結構中定義函數 CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine(myCustomer.WriteName()); //函數的重載,相同函數名,不同的返回值類型和參數類型 double result = MaxValue(1, 2, 3, 4, 5.2); Console.WriteLine("max number {0}", result); //delegate 委托 //定義委托 ProcessDelegate process; Console.WriteLine("Enter 2 numbers separated with a comma:"); string inputString = Console.ReadLine(); int commaPos = inputString.IndexOf(','); double param1 = Convert.ToDouble(inputString.Substring(0, commaPos)); double param2 = Convert.ToDouble(inputString.Substring(commaPos + 1, inputString.Length - commaPos - 1)); Console.WriteLine("Enter M to mutiply or D to Divide:"); inputString = Console.ReadLine(); if (inputString == "M") process = new ProcessDelegate(Multiply);//將委托初始化為函數引用Multiply,可簡寫為process = Multiply; else process = new ProcessDelegate(Divide);//將委托初始化為函數引用Divide,可簡寫為processs = Divide; Console.WriteLine("Result:{0}", process(param1, param2));//使用委托變量調用它引用的函數 Console.ReadKey(); } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。