可选参数:调用参数时,常常需要给方法传参数,例如public List<string> GetValue(string str,bool b1,boolb2){},str是必须参数,如果给b1,b2提供一个默认值,就可以把b1,b2变成可选参数,调用方法时,如果不给b1,b2传值,就使用默认值。默认值必须是字面值,常量或者默认值类型的值。可选参数必须位于方法参数列表末尾。
命名参数:使用可选参数时,可以指定要使用的可选参数。
//命名参数和可选参数
- class WordProcessor
- {
- //可选参数1, 可选参数2 可选参数3
- public static List<string> GetWords (string sentence,bool capitalizeWords=false,bool reverseOrder=false,bool reverseWords=false){
- List<string> words = new List<string>(sentence.Split(' '));
- if (capitalizeWords)//正常输出
- {
- words = CapitalizeWords(words);
- }
- if (reverseOrder)//单词反向输出
- {
- words = ReverseOrder(words);
- }
- if (reverseWords)//全部反向输出
- {
- words = ReverseWords(words);
- }
- return words;
- }
- //按顺序,首字母大写,正常输出文本
- public static List<string> CapitalizeWords(List<string> words) {
- List<string> capw = new List<string>();
- foreach (var word in words)
- {
- if (word.Length==0)
- {
- continue;
- }
- if (word.Length == 1)
- {
- capw.Add(word[0].ToString().ToUpper());
- }
- else {
- capw.Add(word[0].ToString().ToUpper()+word.Substring(1));
- }
- }
- return capw;
- }
- //单词反向输出
- public static List<string> ReverseOrder(List<string> words) {
- List<string> revo = new List<string>();
- for (int wordIndex = words.Count-1; wordIndex>=0; wordIndex--)
- {
- revo.Add(words[wordIndex]);
- }
- return revo;
- }
- //全部反向输出
- public static List<string> ReverseWords(List<string> words) {
- List<string> revw = new List<string>();
- foreach (var word in words)
- {
- revw.Add(ReverseWord(word));
- }
- return revw;
- }
- public static string ReverseWord(string word) {
- StringBuilder sb = new StringBuilder();
- for (int characterInder = word.Length-1; characterInder>=0; characterInder--)
- {
- sb.Append(word[characterInder]);
- }
- return sb.ToString();
- }
- }
- public static void Main(string[] args){
- string sentence = "his gaza against the sweeping bars has" + "grown so weary";
- List<string> words;
- Console.WriteLine("正常文本:");//只有1个必选参数
- words = WordProcessor.GetWords(sentence);
- foreach (var word in words)
- {
- Console.Write(word);
- Console.Write(' ');
- }
- Console.WriteLine();
- Console.WriteLine("有可选参数的文本:");//1个必选参数,2个可选参数
- words = WordProcessor.GetWords(sentence, capitalizeWords: true, reverseOrder: true);
- foreach (var word in words)
- {
- Console.Write(word);
- Console.Write(' ');
- }
- Console.WriteLine();
- }