C#メモ 可変な引数を受け取るメソッドを作ってみる

CやC++のprintf()メソッドみたく、可変な引数を持つメソッドを作ってみたくてね。
ポイントはこんだけ。

  • 引数にparamsを指定する

んで、メソッドはこんな感じ。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public void Function(params string[] values)
{
// 引数の数だけ引数の文字列をコンソールへ出力する
for (int current = 0; current < values.Length;current++ )
{
System.Console.WriteLine("values[{0}] : {1}", current, values[current]);
}
}
public void Function(params string[] values) { // 引数の数だけ引数の文字列をコンソールへ出力する for (int current = 0; current < values.Length;current++ ) { System.Console.WriteLine("values[{0}] : {1}", current, values[current]); } }
public void Function(params string[] values)
{
	// 引数の数だけ引数の文字列をコンソールへ出力する
	for (int current = 0; current < values.Length;current++ )
	{
		System.Console.WriteLine("values[{0}] : {1}", current, values[current]);
	}
}

呼び出すのはこんな感じ。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Function("first","second","third");
Function("first","second","third");
Function("first","second","third");

んで、実行結果はこんな感じ。
呼び出したときに引数にしたfirst、second、thirdって文字列がコンソールへ出力されとる。

21900_01

んまま、メモってことで。