Csharp/C#教程:用于.NET 3.5的Lazy 的实现分享


用于.NET 3.5的Lazy 的实现

.NET 4.0有一个很好的实用程序类,名为System.Lazy ,它执行惰性对象初始化。 我想将这个类用于3.5项目。 有一次我在stackoverflow的答案中看到某个实现,但我再也找不到了。 有人有Lazy的替代实现吗? 它不需要框架4.0版本的所有线程安全function。

更新:

答案包含非线程安全和线程安全版本。

这是我使用的实现。

///  /// Provides support for lazy initialization. ///  /// Specifies the type of object that is being lazily initialized. public sealed class Lazy { private readonly object padlock = new object(); private readonly Func createValue; private bool isValueCreated; private T value; ///  /// Gets the lazily initialized value of the current Lazy{T} instance. ///  public T Value { get { if (!isValueCreated) { lock (padlock) { if (!isValueCreated) { value = createValue(); isValueCreated = true; } } } return value; } } ///  /// Gets a value that indicates whether a value has been created for this Lazy{T} instance. ///  public bool IsValueCreated { get { lock (padlock) { return isValueCreated; } } } ///  /// Initializes a new instance of the Lazy{T} class. ///  /// The delegate that produces the value when it is needed. public Lazy(Func createValue) { if (createValue == null) throw new ArgumentNullException("createValue"); this.createValue = createValue; } ///  /// Creates and returns a string representation of the Lazy{T}.Value. ///  /// The string representation of the Lazy{T}.Value property. public override string ToString() { return Value.ToString(); } } 

如果您不需要线程安全,那么将它与工厂方法放在一起非常容易。 我使用的非常类似于以下内容:

 public class Lazy { private readonly Func initializer; private bool isValueCreated; private T value; public Lazy(Func initializer) { if (initializer == null) throw new ArgumentNullException("initializer"); this.initializer = initializer; } public bool IsValueCreated { get { return isValueCreated; } } public T Value { get { if (!isValueCreated) { value = initializer(); isValueCreated = true; } return value; } } } 

aaron的简化版本

 public class Lazy where T : new() { private T value; public bool IsValueCreated { get; private set;} public T Value { get { if (!IsValueCreated) { value = new T(); IsValueCreated = true; } return value; } } } 

可以添加一些有趣(但不是非常有用)的东西:来自委托的隐式转换:

 public static implicit operator Lazy(Func initializer) { return new Lazy(initializer); } 

和用法

 private static Lazy Value = new Func(() => 24 * 22); 

C#编译器在执行此转换时遇到一些问题,例如分配lambda表达式不起作用,但它还有一件事让你的大家有点思考:)

上述就是C#学习教程:用于.NET 3.5的Lazy 的实现分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1015631.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐