Best way to dispose a list(处理列表的最佳方式)
问题描述
我有 List 对象.我该如何处理清单?
I am having List object. How can I dispose of the list?
例如,
List<User> usersCollection =new List<User>();
User user1 = new User();
User user2 = new User()
userCollection.Add(user1);
userCollection.Add(user2);
如果我设置 userCollection = null;
会发生什么?
If I set userCollection = null;
what will happen?
foreach(User user in userCollection)
{
user = null;
}
哪个最好?
推荐答案
最好的办法是把它留给垃圾收集器.您的 foreach
将什么也不做,因为只有引用将设置为 null
而不是列表中的元素.将列表设置为 null
实际上可能会导致垃圾收集发生的时间比它可能的时间晚(请参阅这篇文章 C#: 对象变量应该赋值给null吗?).
Best idea is to leave it to the garbage collector.
Your foreach
will do nothing since only the reference will be set to null
not the element in the list. Setting the list to null
could in fact cause garbage collection to occur later than it could have (see this post C#: should object variables be assigned to null?).
这篇关于处理列表的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理列表的最佳方式


基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01