using System; using System.Collections.Generic; namespace MethodLesson { class MainClass { public static void Main(string[] args) { Console.WriteLine(ShowInfo());//ゴンベ(20) Console.WriteLine(ShowInfo("山田"));//山田(20) Console.WriteLine(ShowInfo("山田", 22)); //名前付き引数 Console.WriteLine(ShowInfo(age: 30)); Console.WriteLine(ShowInfo(age:40, name:"田中")); //可変長引数 Console.WriteLine(CalcAdd(2,3,5)); Console.WriteLine(CalcAdd()); Console.WriteLine(CalcAdd(2, 4, 4, 3)); //Console.WriteLine(CalcAdd2()); Console.WriteLine(CalcAdd2(2,3,4,5)); } //引数の既定値 public static string ShowInfo(string name = "ゴンベ", int age = 20) { return $"{name}({age})"; } //可変長引数 public static int CalcAdd(params int[] data){ int sum = 0; foreach(var n in data){ sum += n; } return sum; } //Calcメソッドは必ず1つ以上の引数を受け取るように改良 public static int CalcAdd2(int first,params int[] data) { int sum = first; foreach (var n in data) { sum += n; } return sum; } } }
コメント