无法将 System.Object[] 转换为 System.Collections.Generic.List
我有一个带有对象参数的方法。
public bool ContainsValue(object value)
我发现将对象转换为 IList
是有效的。
IList<object> list = (IList<object>)value;
但是,将其转换为 List
却不会。
List<object> Ilist = (List<object>)value;
我查看了 IList
和 List
的定义,它们似乎都实现了 Enumerator
和 Collection
接口。我想知道为什么 List
不起作用,但 IList
却起作用。它在框架的哪个位置崩溃了,为什么?
I have a method with an object parameter.
public bool ContainsValue(object value)
I found that converting the object to an IList
works.
IList<object> list = (IList<object>)value;
However, converting it to a List
does not.
List<object> Ilist = (List<object>)value;
I looked at the definition of both the IList
and the List
and they both seem to implement the Enumerator
and Collection
interfaces. I am wondering why List
doesn't work but IList
does. Where in the framework does it crash and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是 C# 专家,但可能
IList
是一个接口,而List
是一个实现?它可能是IList
的另一个实现...Not a C# expert, but might it be that
IList
is an interface whileList
is an implementation? It might be another implementation ofIList
...如果一个对象实现了IList接口,并不意味着它实际上是List类型。它可以是实现 IList 接口的任何其他类型。
If an object implements the IList interface, it doesn't mean that it is actually of the type List. It can be any other type implementing the IList interface.
正如其他人所说,您有两个问题:
IList
不一定是List
。ContainsValue
的参数可能应该比object
更具体。但是,如果由于某种原因参数必须保留为
对象
,并且您需要一个List
,而不是IList
>,你可以这样做:As others have said, you have two problems:
IList
is not necessarily aList
.ContainsValue
should probably be something more specific thanobject
.However, if for some reason the parameter must remain and
object
, and you require aList
, rather than anIList
, you can do this: