处理列表的最佳方式 [英] Best way to dispose a list

查看:20
本文介绍了处理列表的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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?).

这篇关于处理列表的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆