在什么情况下System.Collections.Generic.List中的项目不会被成功删除?
在什么情况下System.Collections.Generic.List中的项目不会被成功删除?
来自http://msdn.microsoft.com/en-us/library/cd666k3e。 .aspx:
如果项目已成功删除,则为 true; 否则为假。这个方法还 如果在以下位置找不到项目,则返回 false 列表(T)。
他们的措辞方式让我认为对 List(Of T) 中找到的项目进行删除操作实际上可能会失败,因此出现了这个问题。
in what situation will an item in System.Collections.Generic.List not be removed successfully?
From http://msdn.microsoft.com/en-us/library/cd666k3e.aspx:
true if item is successfully removed;
otherwise, false. This method also
returns false if item was not found in
the List(Of T).
The way they phrase it makes me think that it is possible that a Remove operation on an item found in the List(Of T) could actually fail, hence this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看 Reflector 中的 System.Collections.Generic.List 源,看起来在集合中未找到的项目确实是 Remove 返回 false 的唯一方法。
Looking at the System.Collections.Generic.List source in Reflector, it would appear that the item not being found in the collection is indeed the only way for Remove to return false.
上面的代码通过反射器。仅当不在集合中时才不会被删除。我猜测文档/语言存在差异。
Code above via reflector. Will only not be removed if it wasn't in the collection. I'm guessing a documentation/language discrepancy.
是的,如果您尝试删除不在列表中的项目,它会被归类为失败并返回 false 以表明您没有删除任何内容。
如果您确实删除了某些内容,然后想要执行其他代码,这可能会很有用。
更新:如果您的类实现 IEquality 并引发异常,则代码会允许引发异常,因为它没有机会返回。
再加上其他人发布反射源,只有当它找不到项目时才返回 false。
更新:进一步参考其他人的来源。如果您查看
IndexOf
方法链,您会发现它归结为相等并且没有做任何特殊的事情。List.Remove:
List.IndexOf:
Array.IndexOf:
EqualityComparer.IndexOf:
所有代码均来自 ILSpy,不感谢 Red Gate :-)
Yes it can, if you are trying to remove an item that isn't in the list - it is classed as a fail and returns false to show you that nothing was removed.
This can be useful if you then want to do other code if something was actually removed.
Update: if your class implements IEquality and that throws an exception, the code lets the throw occur, as in it doesn't get a chance to return.
Coupled with others posting the reflected source, returning false is only when it cannot find an item.
Update: further to other people's source. If you look at the
IndexOf
chain of methods, you will see that it boils down to equality and does nothing special.List.Remove:
List.IndexOf:
Array.IndexOf:
EqualityComparer.IndexOf:
All code from ILSpy, no thanks to Red Gate :-)
在Mono的源代码中进行比较:
https://github.com/mono/mono/raw/master/mcs/class/corlib/System.Collections.Generic/List.cs
所以,文档过于模糊
In Mono's source code for comparison:
https://github.com/mono/mono/raw/master/mcs/class/corlib/System.Collections.Generic/List.cs
So, the documentation is overly fuzzy