猿问

什么时候应该使用Lazy <T>?

我发现了这篇文章Lazy:C#4.0中的惰性-惰性


使用惰性对象具有最佳性能的最佳实践是什么?有人可以指出我在实际应用中的实际用途吗?换句话说,什么时候应该使用它?


眼眸繁星
浏览 773回答 3
3回答

呼啦一阵风

通常,当您想在第一次实际使用某个实例时实例化它。这将创建它的成本延迟到需要时/而不是始终产生成本。通常,当可以使用或不使用该对象并且构造它的成本很重要时,这是优选的。

函数式编程

您应该尝试避免使用Singleton,但是如果需要,Lazy<T>可以轻松实现懒惰的,线程安全的Singleton:public sealed class Singleton{&nbsp; &nbsp; // Because Singleton's constructor is private, we must explicitly&nbsp; &nbsp; // give the Lazy<Singleton> a delegate for creating the Singleton.&nbsp; &nbsp; static readonly Lazy<Singleton> instanceHolder =&nbsp; &nbsp; &nbsp; &nbsp; new Lazy<Singleton>(() => new Singleton());&nbsp; &nbsp; Singleton()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Explicit private constructor to prevent default public constructor.&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }&nbsp; &nbsp; public static Singleton Instance => instanceHolder.Value;}
随时随地看视频慕课网APP
我要回答