【发布时间】:2012-09-25 13:29:58
【问题描述】:
延迟实例化是否使用更少的代码但获得相同的结果?当然,这通常是一件好事(只要使代码简短/高效不会损害可读性/可维护性)。
请参考这个惰性实例化:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Instance 没有私有属性(我知道这是隐含的)- 是不是让它变得懒惰- 事实上我们在 public static Singleton Instance 属性中没有设置器?
【问题讨论】:
-
你为什么不用
Lazy<T>?看看这篇文章:msdn: lazy initialization -
我已经读过 - 问题是我不经过测试就无法理解,并且在工作中我们只在 .Net 2.0 上(所以我不能使用
) - 不要问!! -
@DaveRook:这是
Lazy<Singleton>:stackoverflow.com/a/6847882/284240