【发布时间】:2018-07-19 02:24:35
【问题描述】:
所以我在 C# 中遇到了通用列表的问题:
var foo = new Dictionary<long, List<object>>();
foo.Add(123, new List<string>());
给出错误:Cannot convert from System.Collections.Generic.List<string> to System.Collections.Generic.List<object>
在哪里可以正常工作:
var foo = new Dictionary<long, object>();
foo.Add(123, new string());
我的真实用例如下所示:
var foo = new Dictionary<long, List<ISomeInterface>>();
foo.Add(123, new List<SomeClassA>());
foo.Add(345, new List<SomeClassB>());
SomeClassA 和 SomeClassB 都实现了 ISomeInterface。这可能吗?
我的想法是我可以从字典中获取 ISomeInterface 列表并迭代调用在 ISomeInterface 上定义的 SomeMethod 的列表。
【问题讨论】:
-
你想要的是协方差,它只适用于接口。所以
Dictionary<long, IEnumerable<object>>会起作用,但当然你只能从字典的值中取出项目,但这是为了确保你不会将字符串放入实际的 int 列表中。 -
不确定这对您的情况是否有帮助,但您可以声明
List<ISomeInterface>类型的列表并用SomeObject的实例填充它,然后将其添加到Dictionary跨度> -
如果您需要知道接口的具体类型,那就是代码异味。您应该通过接口的 API 将任何类似的类类型逻辑推送到类中。
-
@juharr 说的是对的,但你也可以使用
Dictionary<long, IReadOnlyList<ISomeInterface>>