.NET 4.0 有一个很好的实用程序类,叫做 System.Lazy执行惰性对象初始化。我想将此类用于 3.5 项目。有一次我在 stackoverflow 答案的某个地方看到了一个实现,但我再也找不到了。有人有 Lazy 的替代实现吗?它不需要框架 4.0 版本的所有线程安全功能。
更新:
答案包含非线程安全版本和线程安全版本。
最佳答案
这是我使用的一个实现。
/// <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();
}
}
关于c# - .NET 3.5 的 Lazy<T> 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3207580/