【发布时间】:2026-02-17 03:55:01
【问题描述】:
在我的示例中,我有许多扩展基类 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: '无法转换类型的对象 'Example.Fruit[]' 输入 'System.Collections.Generic.IEnumerable`1[Example.Orange]'。'
我该如何做我想做的事?
【问题讨论】:
标签: c# .net dictionary generics