我正在研究 Jon Skeet 的 Edulinq,我看到了以下代码,第 23 页,他在其中为 Linq 的 Empty()
运算符实现了缓存机制
private static class EmptyHolder<T>
{
internal static readonly T[] Array = new T[0];
}
我的问题是,这实际上是如何缓存 Array
变量的?
可选,它在 CLR 中如何工作?
编辑:在此之后,他还提到有人反对返回数组。为什么任何人都不应该返回一个数组(即使它的大小为 0?)?
最佳答案
My question is, how does this actually cache the Array variable?
CLR 根据类型参数缓存它。基本上,EmptyHolder<int>
是与 EmptyHolder<string>
不同的类型等等,并且类型初始值设定项被调用(自动,由 CLR)每个具体类型。
所以:
var x = EmptyHolder<string>.Array; // Needs to construct the empty string[] array
var y = EmptyHolder<string>.Array; // No extra work! x and y have the same value
var z = EmptyHolder<int>.Array; // This constructs an empty array for int[]
Optionally, How does it work in CLR?
恐怕这是我不太了解的实现细节。但基本上,这就是关于 CLR 如何做事的全部:)
Edit: Also following that, he mentions there was a revolt against returning an array. Why should anybody not return an array (even if it is 0 sized?)?
嗯,有评论:
The array method is not so great: People will incorrectly depend on the return value being an array although this is not documented.
我个人认为这不是问题,但编写替代实现很有趣 :)
关于c# - Jon Skeet 的 Edulinq - 空数组缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14733786/