c# - 创建通用类型的字典

标签 c# .net dictionary generics

在我的示例中,我有许多扩展基类 Orange 的类( PearAppleFruit ……) .

我正在创建一个模型类,其中包含 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/

相关文章:

c# - 无法在 ASP.NET Core 2 应用程序上注销 identityserver4 的 OpenIdConnect 身份验证

c# - 是否有支持 "made up"Unicode 组合字符的字体?

c# - 返回实现通用接口(interface)的类的类型

javascript - 如何在 map 上使用 Object.observe?

c# - 微软编码风格问题

c# - 无法让 RestSharp 与 DELETE 和 RequestBody 一起工作

c# - 将不同的数字类型作为参数发送到方法时是否存在性能问题?

c# - 使用 C# 的嵌入式 FTP 服务器?

dictionary - 实现 mapTree 功能

Matlab:指定的值类型与该容器的预期类型不匹配