带有字典的自定义 Class 上的 NullReferenceException

NullReferenceException on custom Class with Dictionary

我今天有一个简单的问题,关于某些未按预期工作的自定义 类。对于上下文,这是 Xamarin Forms 中的 C# 代码,为 UWP 构建。

在我的 C# 代码中,我有两个自定义 classes。我们称它们为更小和更大。 Smaller 是一个简单的 class,它只有几个实例变量。我的问题是 Bigger class,它包括一个将字符串映射到我的 Smaller class 实例的字典。当我尝试为 Bigger class 创建索引器时,我希望它索引到包含在 class.

中的字典中

以下是相关部分的代码:

public class Smaller {
    ... // a bunch of instance variables, all strings, public and private versions.
}

public class Bigger {
    ...
    // other instance variables here...
    ...
    // the dictionary in question, mapping to Smaller instances
    private Dictionary<string, Smaller> _Info;
    public Dictionary<string, Smaller> Info {
        get => _Info;
        set { 
            _Info = value;
            OnPropertyChanged("Info");
        }
    }

    public Smaller this[string key] { // Indexer for Bigger class
        get => _Info[key];
        set => Info.Add(key, value);
    }
}

在索引器中我得到了我的错误,我的 getter 和 setter 上的 NullReferenceException。这里出了什么问题?我已经尝试使用私有 _Info 或 public Info 为 getter 和 setter 两者都工作,但两者都不适用。

OnPropertyChanged 不会影响任何东西,因为我有其他变量使用它们,它们工作正常。我是否应该摆脱两个变量,private 和 public?我这样做是因为代码改编自使用私有和 public 实例的模板。

谢谢!

这是空的

private Dictionary<string, Smaller> _Info;

你需要初始化它

private Dictionary<string, Smaller> _Info = new Dictionary<string, Smaller>();