gpt4 book ai didi

c# - 只读静态字段如何为空?

转载 作者:IT王子 更新时间:2023-10-29 04:15:50 25 4
gpt4 key购买 nike

下面是我的一节课的摘录:

    [ThreadStatic]
readonly static private AccountManager _instance = new AccountManager();

private AccountManager()
{
}

static public AccountManager Instance
{
get { return _instance; }
}

如您所见,它是一个单例线程 - 即该实例标有 ThreadStatic 属性。该实例也被实例化为静态构造的一部分。

既然如此,当我尝试使用 Instance 属性时,怎么可能在我的 ASP.NET MVC 应用程序中收到 NullReferenceException?

最佳答案

引用 MSDN ThreadStaticAttribute :

Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to a null reference (Nothing in Visual Basic) if it is a reference type.

关于c# - 只读静态字段如何为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043461/

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