C# List<T>.IList.Removeの例外動作

List<T>.IList.Removeメソッドで想定外の動作をしていた。

現在、List<T>ライクで別の制約を持たせるコンテナクラスを作成していて、List<T>と同じメソッドを用意するため実装と評価をしているところ。
ほぼほぼ完了したところで、List<T>.IList.Removeに関してだけ、作成したコンテナクラスの動作とList<T>の動作で異なるところが出てきた。

APIリファレンスでは次のようになっている。

List.IList.Remove(Object) Method (System.Collections.Generic)
Removes the first occurrence of a specific object from the IList.

違っている部分は例外に関する部分で、itemが格納オブジェクトと異なるタイプの場合に例外を出すといった内容。

この部分の記述はAdd, Insertともに同じ記述だったため、Add, Insertと同様に例外を出すものだと思ったのだが、Removeでは例外が出なかった。

テスト用のコードは以下の様にした。

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

namespace ListTTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> values = new List<int>() { 1, 3, 5 };

            IList il = values;
            il.Remove(7.9);

            foreach (var val in values) {
                Console.WriteLine(val);
            }

            try {
                il.Add(4.5);
            }
            catch (ArgumentException ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                il.Insert(0, 3.0);
            }
            catch (ArgumentException ex) {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

実行結果は以下の様になった。

1
3
5
The value "4.5" is not of type "System.Int32" and cannot be used in this generic collection. (Parameter 'value')
The value "3" is not of type "System.Int32" and cannot be used in this generic collection. (Parameter 'value')

Removeメソッドに関しては例外が出ず、特に何も処理をせず抜けている。

IList.Remove(Object) Method (System.Collections)
Removes the first occurrence of a specific object from the IList.

IList.RemoveにはNotSupportedExceptionしか例外の記述がないので、ArgumentExceptionが出るという記述は間違いなんだろうと思う。
実際IList<T>のソースを見ると、例外は出すような実装にはなっていなかったようなので。

コメント

タイトルとURLをコピーしました