いくつかのユニットテストを書いているうちに、私は奇妙なことがあります。辞書<TKey,TValue>:テレビの正確なタイプは、あなたが入れたものによって決まります
私はDictionary<string, IEnumerable<string>>
を持っています。
テストAssert.IsType<Dictionary<string, IEnumerable<string>>>(result)
が合格です。
ただし、Assert.IsType<IEnumerable<string>>(result["myKey"])
は失敗します。 代わりにSystem.String[]
だったはずです。
私は確認のためのクイックコンソールアプリを書いて、さらに驚いてくれました。 string[]
またはList<string>
を追加した場合、値のタイプが異なりました。生じた
var dic = new Dictionary<string, IEnumerable<string>>();
dic.Add("myArrayKey", new[] { "Value1", "Value2" });
dic.Add("myListKey", new List<string> { "Value1", "Value2" });
Console.Write("Type of dic should be Dictionary<string, IEnumerable<string>> : ");
Console.WriteLine(dic.GetType());
Console.Write("Type of dic[myListKey] should be IEnumerable<string> : ");
Console.WriteLine(dic["myArrayKey"].GetType());
Console.Write("Type of dic[myArrayKey] should be IEnumerable<string> : ");
Console.WriteLine(dic["myListKey"].GetType());
:
Type of dic should be Dictionary<string, IEnumerable<string>> : System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.IEnumerable`1[System.String]]
Type of dic[myArrayKey] should be IEnumerable<string> : System.String[]
Type of dic[myListKey] should be IEnumerable<string> : System.Collections.Generic.List`1[System.String]
私はstring[]
とList<string>
両方がIEnumerable<string>
であることを知っているが、結果は、私は全く期待していなかったものです。 誰もこの動作でいくつかの洞察を与えることができますか?
脇役:これを避けるために、Assert.IsType<>
からAssert.IsAssignableFrom<>
にテストを変更しました。
'IEnumerable'があり、 'Cat'と' Dog'型を入れた場合、出てきたときに種を変えたり、どんな種であったのか忘れたりすることはありません。 –