假设你有一个类 Person :
public class Person
{
public string Name { get; set;}
public IEnumerable<Role> Roles {get; set;}
}
我显然应该在构造函数中实例化角色。 现在,我曾经用这样的列表来做:
public Person()
{
Roles = new List<Role>();
}
但是我在System.Linq
命名空间中发现了这个静态方法
IEnumerable<T> Enumerable.Empty<T>();
来自 MSDN :
The
Empty(TResult)()
method caches an empty sequence of typeTResult
. When the object it returns is enumerated, it yields no elements.In some cases, this method is useful for passing an empty sequence to a user-defined method that takes an
IEnumerable(T)
. It can also be used to generate a neutral element for methods such asUnion
. See the Example section for an example of this use of
那么这样写构造函数是不是更好呢?你用吗?为什么?如果不是,为什么不呢?
public Person()
{
Roles = Enumerable.Empty<Role>();
}
最佳答案
我认为大多数帖子都没有捕获要点。即使您使用空数组或空列表,它们也是对象并且存储在内存中。垃圾收集器必须照顾他们。如果您正在处理高吞吐量应用程序,它可能会产生明显的影响。
Enumerable.Empty
不会在每次调用时创建对象,从而减轻 GC 的负载。
如果代码位于低吞吐量位置,则归结为美学考虑。
关于c# - 使用 Enumerable.Empty<T>() 而不是 new List<T>() 来初始化 IEnumerable<T> 是否更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1894038/