Dav*_*ave 5 c# lazy-initialization
懒惰的实例化是关于使用更少的代码但得到相同的结果?当然,这通常是一件好事(提供简短/高效的代码不会损害可读性/可维护性).
请参考这个懒惰的实例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Instance(我知道它是隐含的)没有私有财产- 它是否使它变得懒惰 - 事实上我们在public static Singleton Instance财产中没有设置者?
Moo*_*ght 13
假设我们有一个构造成本昂贵的领域
class Foo
{
public readonly Expensive expensive = new Expensive();
...
}
Run Code Online (Sandbox Code Playgroud)
这段代码的问题在于,实现Foo会导致实现的性能成本Expensive- 无论是否Expensive访问该字段.显而易见的答案是按需构建实例或懒惰地实现该字段:
class Foo
{
Expensive _expensive;
public Expensive
{
get
{
if (_expensive == null) _expensive = new Expensive();
return _expensive;
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
这是懒惰的异化.
不,懒惰的实例化意味着不需要花费任何时间和资源来创建一些东西,直到你真正需要它为止.
在你的单例示例中,instance它只是一个空引用,直到它实际使用.当它的使用,那么你花的资源用实例化对象new.