编译器错误:无法将“List<string>”转换为“IList<object>”。

3
我该如何修改以下代码使其能够编译通过?(除了将strings转换为List<object>之外)
Action<IList<object>> DoSomething = (list) => { /*list is never modified*/ };
var strings = new List<string>() { "one", "two" };
DoSomething(strings);

您是否真的需要它是IList(您只是查看还是修改集合)?DoSomething应该做什么? - NSGaga-mostly-inactive
@NSGaga,在“DoSomething”内部,IList不会被修改。 - Lee Grissom
2个回答

6

正如编译器错误所示,您不能将 IList<string> 强制转换为 IList<object>。这是因为 IList<T> 接口相对于 T不变的。想象一下,如果您的代码像这样:

Action<IList<object>> DoSomething = (list) => list.Add(1);

这在IList<object>中是有效的,但在IList<string>中则无效。
只要您不试图修改集合,一个简单的解决方案是将IList<T>更改为IEnumerable<T>,它与T相关联是协变的
Action<IEnumerable<object>> DoSomething = (list) => { };
var strings = new List<string>() { "one", "two" };
DoSomething(strings);

更多阅读


谢谢,这确实帮助我更好地理解了。我已经标记为答案并会看看能否学习所引用的文章。我还将调查是否可以将代码从IList更改为IEnumerable,因为集合不应该被修改。 - Lee Grissom

2

你需要创建一个新的列表:

DoSomething(strings.OfType<object>().ToList());

如果可以的话,可以使用 Action<IEnumerable<object>>


1
  1. 在这里我会使用 Cast 而不是 OfType,因为你实际上并不想进行任何过滤。
  2. 你可以通过写 strings.ToList<object>() 来完全摆脱 OfType
- svick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接