只读静态字段怎么会空? [英] How can a readonly static field be null?

查看:167
本文介绍了只读静态字段怎么会空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这里是从我的一个类的摘录:

So here's an excerpt from one of my classes:

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

    private AccountManager()
    {
    }

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

正如你所看到的,这是一个单身,每个线程 - 即例如标有ThreadStatic属性。该实例也实例化静态建设的一部分。

As you can see, it's a singleton-per-thread - i.e. the instance is marked with the ThreadStatic attribute. The instance is also instantiated as part of static construction.

所以,既然如此,怎么可能是我得到我的ASP.NET MVC应用程序中的NullReferenceException当我尝试使用实例的属性?

So that being the case, how is it possible that I'm getting a NullReferenceException in my ASP.NET MVC application when I try to use the Instance property?

推荐答案

ThreadStaticAttribute

不要为初始值
  打上领域
  ThreadStaticAttribute,因为这样的
  初始化只发生一次,当
  在类的构造函数执行,并
  因此只影响一个线程。如果
  你不指定一个初始值,
  你可以依靠的字段为
  初始化为它的默认值,如果它
  是值类型,或者为空
  引用(在Visual Basic中为Nothing),如果
  它是一个引用类型。

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.

这篇关于只读静态字段怎么会空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆