- 任意の数の引数を渡せるようにするには、以下のように params キーワードを使います。
public class Test
{
static public void ShowParams(params int[] vals)
{
foreach(int v in vals)
{
Console.WriteLine(v);
}
}
static void Main()
{
ShowParams(new int[] {1,2,3,4,5});
ShowParams(1,2,3,4,5);
}
}
- インデクサは、配列のようなオブジェクトが保持するコレクションに対して、[] の文法を使ってアクセスできる機能です。数字だけでなく、文字や独自クラスなども使ってアクセスすることができます。
public class MyTexts
{
private String[] strings;
public MyTexts(int limit)
{
strings = new String[limit];
}
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length) return null;
return strings[index];
}
set
{
if (index >= strings.Length) return;
strings[index] = value;
}
}
}
- IEnumerable インターフェイスを実装することで、コレクションで foreach を使用することができます。列挙子を作成するキーワード yield は、コルーチンを行っており、foreach( [type] i in is ) で一回りすると、yield まで一回りする、といった感じでしょうか。
public class MyTexts : IEnumerable<String>
{
private string[] strings;
public MyTexts(int limit)
{
strings = new String[limit];
}
...
public IEnumerator<String> GetEnumerator()
{
foreach (string s in strings)
{
yield return s;
}
}
}
public class Test
{
public static Main()
{
MyTexts texts = new MyTexts(3);
texts[0] = "Hello";
texts[1] = "World";
texts[2] = "!";
foreach (String t in texts) { Consol.WriteLine(t); }
}
}