在我的示例中,我有许多扩展基类 Orange
的类( Pear
、 Apple
、 Fruit
……) .
我正在创建一个模型类,其中包含 Fruit
的每种类型的字典。映射到它们的整数 ID。我想避免像这样制作许多字段变量:
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]'.'
我怎样才能做我想做的事?
最佳答案
我想你只需要使用 Cast<T>
来转换它.
return _fruits[typeof(T)].Values.Cast<T>();
使用 (IEnumerable<T>)
转换不起作用,因为它会转换整个东西。您可能已经知道了:List<object>
无法转换为 List<int>
.同样的现象也发生在这里。
因此,我们应该使用Cast<T>
.此方法会将可枚举的每个元素转换为指定的类型,并返回生成的可枚举。
关于c# - 创建通用类型的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364033/