首页 > 解决方案 > c# 在类成员上使用 INotifyPropertyChanged 继承时出现初始化错误

问题描述

我有一个Main类,我在其中定义了另一个类的实例:

namespace testRun
{
    class Main
    {
        /// Initialize object to contain various project data
        public static CurrentState currentState = new CurrentState();
        ...
        public void Event1(object sender, Args e)
        {
            ProcessClear();
        }

        public static void ProcessClear()
        {
            currentState.quantityDictionary.Clear();
        }
}

这个CurrentState类看起来像这样:

namespace testrun
{
        public class CurrentState : INotifyPropertyChanged
        {
            /// Constructor
            public CurrentState() { }

            public event PropertyChangedEventHandler PropertyChanged;

            protected virtual void OnPropertyChanged(string property)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
            }

            private Dictionary<string, double> quantityDictionary;

            private Dictionary<string, double> QuantityDictionary
            {
                get { return quantityDictionary; }
                set
                {
                    quantityDictionary = value;
                    OnPropertyChanged("QuantityDictionary");
                }
            }
       }
}

如果我设置quantityDictionaryPublic,我会收到一条错误消息“Object not set to an instance of an Object”currentState.quantityDictionary.Clear();

我认为这是由于quantityDictionary未正确初始化的面,但我不确定如何正确地做到这一点,或者是否需要在构造函数本身或其他地方完成。对此有点困惑...

有人可以帮我整理一下吗?谢谢

编辑 :

我已将该quantityDictionary字段设置为Private,但如果它不是Public,那么我会CurrentState.quantityDictionary is inaccessible due to its protection levelMain课堂上得到一个currentState.quantityDictionary.Clear();

标签: c#oopconstructorinitializationinotifypropertychanged

解决方案


推荐阅读