C# 配列、コレクション

  • 任意の数の引数を渡せるようにするには、以下のように params キーワードを使います。
public class Test
{
  static public void ShowParams(params int[] vals) //!< params キーワード
  {
    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> //!< インターフェイスIEnumerable<T> の実装
{
  private string[] strings;

  public MyTexts(int limit)
  {
    strings = new String[limit];
  }

  ... //!< 上のインデクサを実装

  public IEnumerator<String> GetEnumerator() //!< メソッドIEnumerable<T>.GetEnumerator()の実装
  {
    foreach (string s in strings)
    {
      yield return s; //!< 列挙子(enumerator)を作成するためのキーワード yield
    }
  }
}

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); }
  }
}