为什么此代码引发ArgumentNullException? [英] Why is this code throwing an ArgumentNullException?

查看:70
本文介绍了为什么此代码引发ArgumentNullException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我全部使用此代码模式,并且仅在此特定属性中,在尝试为其分配值(即调用setter)时会引发ArgumentNullException.为null的对象是isLoggedInLock,因此似乎在调用setter之前尚未实例化该对象.瓦特错了吗?

我注释掉OnPropertyChanged方法以避免混淆.仍然会抛出异常.我可以想到的另一件事是,更新是在UI线程之外的另一个线程中完成的.我在非静态构造函数中实例化了isLoggedInLock,但仍然引发了异常.发生了非常奇怪的事情.我将进一步调查.

最终抱歉,我没有找到解决方案的关键: [DataMember] 属性.该对象通过反序列化而变得栩栩如生.这将跳过默认构造函数和isLoggedInLock的静态初始化.通过使用 [DataMember] 属性修饰isLoggedInLock或通过使用 [OnDeserialzed] 属性修饰的方法实例化isLoggedInLock,问题就解决了!感谢一大堆,第一个更新他的答案的人将获得积分!;-)

I use this code pattern all over and only in this particular property an ArgumentNullException is thrown when trying to assign a value to it (ie invoking the setter). The object being null is the isLoggedInLock,so it seems that it has not been instantiated before the setter is called. Wat is wrong??

I commented out the OnPropertyChanged method to avoid confusion. The exception is still thrown. One other thing I can think of is that the update is done in another thread than the UI thread.

I instantiated the isLoggedInLock in the non-static constructor and still the exception is thrown. Something very strange is going on. I will investigate further.

FINAL My apologies: I left out the key to the solution: the [DataMember] Attribute. The object comes into life by being deserialized. This skips the default constructor and the static initialisation of the isLoggedInLock. By adorning the isLoggedInLock with the [DataMember] attribute or by instantiating it in a method adorned with the [OnDeserialzed] attribute the problem goes away!

Thanks a bunch and the first to update his answer will get the points! ;-)

    [DataMember]
    private bool isLoggedIn;
    private readonly object isLoggedInLock=new object();
    public bool IsLoggedIn
    {
        get
        {
            lock (isLoggedInLock)
            {
                return isLoggedIn; 
            }
        }
        set
        {
            lock (isLoggedInLock)
            {
                isLoggedIn = value;
                //OnPropertyChanged("IsLoggedIn");
            }
        }
    }

推荐答案

即使类的字段在构造函数中初始化,也可能为null:通过反序列化生活,构造函数被称为 not ....

It is possible that a field of a class is null, even when it is initialized in the constructor: when the class comes into life through deserialization, the constructor is not called....

这篇关于为什么此代码引发ArgumentNullException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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