在我的示例中,我有很多擴展基類Fruit
的類(Orange
,Pear
,Apple
,...)。創建泛型類型的字典
我正在創建一個模型類,其中包含映射到其整數ID的每種類型Fruit
的字典。我想,以避免使許多字段變量是這樣的:
Dictionary<int, Orange> _oranges = new Dictionary<int, Orange>();
我想我也許可以創造一個「通用」的字典,我在其中映射等辭書到Fruit
類型:
Dictionary<Type, Dictionary<int, Fruit>> _fruits = new Dictionary<Type, Dictionary<int, Fruit>>();
要插入此結構中,我使用的方法,像這樣:
public void Insert(Fruit fruit)
{
_fruits[fruit.GetType()][fruit.Id] = fruit;
}
問題是當我嘗試檢索存儲的值,在此方法:
public IEnumerable<T> GetFruits<T>() where T : Fruit
{
return (IEnumerable<T>) _fruits[typeof(T)].Values.ToArray();
}
這將被稱爲像GetFruits<Orange>()
。演員失敗並出現此錯誤:
System.InvalidCastException: 'Unable to cast object of type 'Example.Fruit[]' to type 'System.Collections.Generic.IEnumerable`1[Example.Orange]'.'
我該怎麼做我想做的事?
另外/可替代地,也可以使用['OfType'](https://stackoverflow.com/a/41951319/314291)來過濾的類型,並避免可能的InvalidCast異常 – StuartLC
謝謝,這正是我想要的,我明白爲什麼我的代碼不工作之前:) –