在我的示例中,我有很多扩展基类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
谢谢,这正是我想要的,我明白为什么我的代码不工作之前:) –