小编dim*_*r.d的帖子

在 C# List<T> 实现中使用 `static readonly T[] _emptyArray = new T[0]` 作为零值

当我发现一些我不完全理解的东西时,我正在阅读C#.Net Core中List<T>的实现。static readonly T[] _emptyArray = new T[0]每次底层数组 ( private T[] _items) 应保持(或设置为)为空时,都会使用一个字段。例如,在采用容量参数的构造函数重载中:

 public List(int capacity) {

        /*  Checking if capacity is less then 0  */

        if (capacity == 0)
            _items = _emptyArray;
        else
            _items = new T[capacity];
    }
Run Code Online (Sandbox Code Playgroud)

这是某种内存优化模式,因为我没有看到任何其他原因可以使用它,而不是简单地将底层数组设置为新的空数组:_items = new T[0]

c# .net-core

1
推荐指数
1
解决办法
53
查看次数

标签 统计

.net-core ×1

c# ×1