c# - C# 中的惰性字典属性

标签 c# properties lazy-initialization

我有一个带有字典属性的类:

public class Entity 
{
    public Dictionary<string, string> Name { get; set; }
}

我想将此属性切换为使用惰性初始化。我尝试了以下方法:

public class Entity 
{
    private Lazy<Dictionary<string, string>> name = new Lazy<Dictionary<string, string>>(() => new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
    public Dictionary<string, string> Name
    {
        get => name;
        set => name = value;
    }
}

这当然是一个错误,因为 Name 和 name 有不同的类型。不过,对于我的一生,我无法弄清楚如何正确指定它。我真正想要的是让 Name 保持为空,直到我访问它,然后在第一次读取或写入时创建它。

最佳答案

您可以使用 Lazy 进行初始化,但您想要的非常简单,您可以简单地这样做

private Dictionary<string, string> _name;
public Dictionary<string, string> Name
{
    get
    {
        if (_name == null)
            _name = new Dictionary<string, string>();
        return _name;
    }
    set _name = value;
}

编辑:请注意,这种方法会有一些线程安全问题。检查这对您来说是否是个问题。

关于c# - C# 中的惰性字典属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10002957/

相关文章:

c# - 如何删除表中的这种冗余?

c# - 如何编写组合字符的正则表达式?

javascript - 解构一个属性为 "delete"的对象

java - 如何在 Spring 应用程序中延迟加载 LDAP 配置。

swift - 懒惰的 Var 与 Let

c# - 尝试关闭事件的 TCP 连接,但出现错误

c# - 为什么 C# 不允许 const 和 static 在同一行?

ios - 如何本地化 plist 文件

properties - 嵌入在 UIScrollView 中的 UIImageView 和 UIImage 属性的强或弱声明?

swift 2.0 : infer closure type error