T&GT;&懒LT的执行情况;对于.NET 3.5 [英] Implementation of Lazy<T> for .NET 3.5
本文介绍了T&GT;&懒LT的执行情况;对于.NET 3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.NET 4.0有一个名为 System.Lazy 一个很好的工具类,做懒对象初始化。我想使用这个类为3.5的项目。有一次我看到某处的实施在计算器的答案,但我无法找到它了。是否有人有另一种实现懒惰的?它并不需要所有的框架4.0版本的线程安全功能。
.NET 4.0 has a nice utility class called System.Lazy that does lazy object initialization. I would like to use this class for a 3.5 project. One time I saw an implementation somewhere in a stackoverflow answer but I can't find it anymore. Does someone have an alternative implementation of Lazy? It doesn't need all the thread safety features of the framework 4.0 version.
更新:
解答包含非线程安全的,一个线程安全的版本。
Answers contain a non thread safe and a thread safe version.
推荐答案
下面是我使用的实现。
/// <summary>
/// Provides support for lazy initialization.
/// </summary>
/// <typeparam name="T">Specifies the type of object that is being lazily initialized.</typeparam>
public sealed class Lazy<T>
{
private readonly object padlock = new object();
private readonly Func<T> createValue;
private bool isValueCreated;
private T value;
/// <summary>
/// Gets the lazily initialized value of the current Lazy{T} instance.
/// </summary>
public T Value
{
get
{
if (!isValueCreated)
{
lock (padlock)
{
if (!isValueCreated)
{
value = createValue();
isValueCreated = true;
}
}
}
return value;
}
}
/// <summary>
/// Gets a value that indicates whether a value has been created for this Lazy{T} instance.
/// </summary>
public bool IsValueCreated
{
get
{
lock (padlock)
{
return isValueCreated;
}
}
}
/// <summary>
/// Initializes a new instance of the Lazy{T} class.
/// </summary>
/// <param name="createValue">The delegate that produces the value when it is needed.</param>
public Lazy(Func<T> createValue)
{
if (createValue == null) throw new ArgumentNullException("createValue");
this.createValue = createValue;
}
/// <summary>
/// Creates and returns a string representation of the Lazy{T}.Value.
/// </summary>
/// <returns>The string representation of the Lazy{T}.Value property.</returns>
public override string ToString()
{
return Value.ToString();
}
}
这篇关于T&GT;&懒LT的执行情况;对于.NET 3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文