gpt4 book ai didi

c# - 在单例类中引用私有(private)单例属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:15 25 4
gpt4 key购买 nike

<分区>

在下面看到的单例类的情况下,初始化 MyList 的正确方法是什么?我是直接引用字段 MyList(选项 1)还是 Instance.MyList(选项 2)?这里的最佳做法是什么?我的直觉说通过 Instance,但我在事后猜测自己,无法在任何地方找到明确的答案。

public class Foo
{
private readonly static Lazy<Foo> _instance =
new Lazy<Foo>(() => new Foo());

private List<string> MyList;

public static Foo Instance
{
get { return _instance.Value; }
}

private Foo()
{
MyList = new List<string> {"a","b","c"}; //Option 1

Instance.MyList = new List<string> {"a","b","c"}; //Option 2
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com