コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】独自のクラスでコレクション初期化子を使用できるようにする その2

概要

using System;
using System.Collections;
using System.Collections.Generic;

class MyList : IEnumerable
{
    private List<int> mList = new List<int>();

    public void Add( int item )
    {
        mList.Add( item );
    }

    public void Add( int item1, int item2 )
    {
        mList.Add( item1 );
        mList.Add( item2 );
    }

    public void Add( int item1, int item2, int item3 )
    {
        mList.Add( item1 );
        mList.Add( item2 );
        mList.Add( item3 );
    }

    public void Add( params int[] collection )
    {
        mList.AddRange( collection );
    }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main()
    {
        //var myList = new MyList();
        //myList.Add( 1 );
        //myList.Add( 2, 3 );
        //myList.Add( 4, 5, 6 );
        //myList.Add( 7, 8, 9, 10 );
        
        var myList = new MyList
        {
            1, 
            { 2, 3 }, 
            { 4, 5, 6 }, 
            { 7, 8, 9, 10 }, 
        };
    }
}
  1. IEnumerable インターフェイスを実装する
  2. Add 関数を定義する

これらの条件を満たすと、独自クラスでも
コレクション初期化子が使用できるようになりますが、
Add関数に複数の引数を必要とする場合にも
コレクション初期化子で記述することができます

関連記事