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?).
这篇关于处理列表的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理列表的最佳方式


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01