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?).
这篇关于处理列表的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理列表的最佳方式
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
