关于形参的可变参数
學(xué)習(xí)了C#4.0的新特性:可選參數(shù)、命名參數(shù)、參數(shù)數(shù)組。
1、可選參數(shù),是指給方法的特定參數(shù)指定默認(rèn)值,在調(diào)用方法時可以省略掉這些參數(shù)。
但要注意:
(1)可選參數(shù)不能為參數(shù)列表的第1個參數(shù),必須位于所有的必選參數(shù)之后(除非沒有必選參數(shù));
(2)可選參數(shù)必須指定一個默認(rèn)值,且默認(rèn)值必須是一個常量表達(dá)式,不能為變量;
(3)所有可選參數(shù)以后的參數(shù)都必須是可選參數(shù)。
2、命名參數(shù), 是指通過命名參數(shù)調(diào)用,實參順序可以和形參不同。
3、參數(shù)數(shù)組,通過關(guān)鍵字params定義參數(shù)數(shù)組。調(diào)用時可以傳入個數(shù)不同的實參,具備很好的靈活性。
4、具體代碼:
??????? //可選參數(shù) ???????
static int Add(int a, int b = 2) ???????
{ ??????????? return a + b; ??????? } ???????
//參數(shù)數(shù)組,關(guān)鍵字params ???????
static int Add(params int[] p) ???????
{ ??????????? int sum=0; ???????????
foreach (int i in p) ???????????????
sum += i; ???????????
return sum; ???????
}
???????
static void Main(string[] args) ???????
{ ???????????
Console.WriteLine(Add(1)); ???????????
Console.WriteLine(Add(1, 3)); ???????????
//通過命名參數(shù)調(diào)用,實參順序可以和形參不同 ???????????
Console.WriteLine(Add(b:6, a:1)); ???????????
//調(diào)用使用了參數(shù)數(shù)組的方法 ???????????
Console.WriteLine(Add(1, 3,5)); ???????????
Console.WriteLine(Add(1, 3, 5,7)); ???????????
Console.ReadKey(); ??????? }
轉(zhuǎn)載于:https://www.cnblogs.com/yjzh000/p/3178375.html
總結(jié)
- 上一篇: mov sreg, r/m16 在16位
- 下一篇: ie6 PNG图片透明