c# - .NET 3.5 的 Lazy<T> 实现

标签 c# generics lazy-loading

.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/

相关文章:

.net - 为什么运行时将泛型类型显示为 "GenericType` n"?

java - 无法写入 JSON : failed to lazily initialize a collection of role: com. Managem.model.Region.pays,无法初始化代理 - 无 session

c#如何使用linq通过过滤一些数据来获取xml字符串?

c# - 如何将用户控件加载到 splitcontainer.panel2 中?

generics - Typedef函数中的泛型

c++ - 模板中的 typename U = equal_to<T> 是什么意思? STL equal_to<T> 用法

c# - 很好地处理空值的语法

c# - 如何在 ApiController 中为单个方法返回 JSON?

c# - 来自数据库的数据未返回,但正常列表是

php - DI 无法实现延迟加载吗?