NullReferenceException的自定义类与字典



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

在我的c#代码中,我有两个自定义类。我们称它们为更小和更大。small是一个简单的类,它只有几个实例变量。我的问题在于Bigger类,它包含一个将字符串映射到较小类实例的字典。当我尝试为Bigger类创建Indexer时,我希望它索引到类中包含的字典中。 以下是相关部分的代码:
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);
}
}

它是在索引,我得到我的错误,NullReferenceException对我的getter和setter。这里出了什么问题?我已经尝试过使用私有_Info或公共Info的getter和setter,但两者都不适用。

OnPropertyChanged不影响任何东西,因为我有其他的变量使用他们的工作很好。我应该摆脱两个变量,私有和公共吗?我只是这样做,因为代码是从使用私有和公共实例的模板改编的。

谢谢!

这是null

private Dictionary<string, Smaller> _Info;

你需要初始化它

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

最新更新