Using the “clear” method vs. New Object

前端 未结 5 1969
有刺的猬
有刺的猬 2020-12-05 17:13

In the .NET framework, many of the System.Collection classes have Clear methods on them. Is there a clear advantage on using this versus replacing the reference

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 18:06

    Brian is correct but to be more specific, the Clear method removes all items from the current instance of the collection. Instantiating a new collection and assigning its reference to your variable will give you an entirely new instance altogether and may cause some unintended consequences depending on whether or not other people are holding a reference to the old instance. If another thread has a reference to that collection they will still hold a reference to the old collection even though you have created a new instance.

提交回复
热议问题