加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 设置属性值时的NullReferenceException

发布时间:2020-12-15 20:51:59 所属栏目:百科 来源:网络整理
导读:using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication3{ class Cls : INotifyPropertyChanged { private string my; public string
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Cls : INotifyPropertyChanged
    {
        private string my;
        public  string MyProperty
        {
            get
            {
                return my;
            }
            set
            {
                my = value;
                PropertyChanged(this,new PropertyChangedEventArgs("MyProperty")); 
            }

        }

        public Cls()
        {
            MyProperty = "Hello";
        }

        public void print()
        {
            Console.WriteLine(MyProperty);
        }

        protected virtual void OnPropertyChanged(string name)
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;

    }

    class Program
    {
        static void Main(string[] args)
        {
            Cls s = new Cls();
            s.print();
        }
    }
}

当我运行此代码时,它给出:

Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object.

当我不使用INotifyPropertyChanged它工作正常.我不明白问题的原因.

解决方法

没有人会收听??PropertyChanged,在尝试调用它时它将为null.改为使用OnPropertyChanged方法:

private void OnPropertyChanged(string propertyName){
    var handler = PropertyChanged;
    if (handler != null)
        handler(this,new PropertyChangedEventArgs(propertyName));

    // With C# 6 this can be replaced with
    PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}

public  string MyProperty
{
    get { return my; }
    set
    {
       if (my == value)
           return;

        my = value;
        OnPropertyChanged("MyProperty");
    }
}

要避免它为null,您必须订阅它,例如从您的main方法:

static void Main(string[] args){
    Cls s = new Cls();
    s.PropertyChanged += (sender,args) => MessageBox.Show("MyProperty changed!");
    s.print();
}

这是一种奇特的写作方式

static void Main(string[] args){
    Cls s = new Cls();
    s.PropertyChanged += ShowMessage;
    s.print();
}

private void ShowMessage(object sender,PropertyChangedEventArgs args){
    MessageBox.Show("MyProperty changed!");
}

无论你怎么说都清楚.
您可以阅读有关事件here的更多信息

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读