我得到一个空引用异常,但不知道为什么(见代码)。
我有以下代码作为我正在制作的反序列化器的一部分。当我的类的反序列化实例缺少某些键时,以下代码将默认键/值添加到一组字典中。这样做的原因是,当客户部署我的插件的新版本时,即使他们没有所有密钥,他们的旧设置仍然会正确反序列化。
这是我的代码:
private Dictionary<string, T> AddMissingSettings<T>(Dictionary<string, T> settingsObject, bool forceDefaults, string[] settingsList)
{
if (forceDefaults || settingsObject == null)
{
settingsObject = new Dictionary<string, T>();
}
foreach (string t in settingsList)
{
if (!settingsObject.ContainsKey(t))
{
settingsObject.Add(t, default(T));// Null Reference Exception Here
}
}
return settingsObject;
}
这是我调用该方法的示例:
Dictionary<string, DateTime> Times = getlistoftimesettingsfromdata();
//Note: Not the real way Times gets set, but whatever
Times = AddMissingSettings<DateTime>(Times, forceDefaults, new string[] { "LastEmailUpdate", "IdealRegularReportTime", "LastRegularReport" });
//Also, pretty sure the "Times = " here is redundant, but let it pass
将 VPNd 编辑到工作中以发布我正在使用的实际代码。我可以确认它可以编译并运行。
private void LoadDefaults(bool forceDefaults)
{
if (RegularReportDays == null || forceDefaults) { RegularReportDays = new List<DayOfWeek>(); }
if (RegularReportSubscribers == null || forceDefaults) { RegularReportSubscribers = new List<string>(); }
Times = AddMissingSettings<DateTime>(Times, forceDefaults, DateTime.MinValue, new string[] { "LastEmailUpdate", "IdealRegularReportTime", "LastRegularReport" });
Toggles = AddMissingSettings<bool>(Toggles, forceDefaults, false, new string[] { "AutomaticUpdates", "AutomaticUpdatesAlerts", "SendRegularReports" });
}
private Dictionary<string, T> AddMissingSettings<T>(Dictionary<string, T> settingsObject, bool forceDefaults, T defaultValue, string[] settingsList)
{
if (forceDefaults || settingsObject == null)
{
settingsObject = new Dictionary<string, T>();
}
foreach (string t in settingsList)
{
if (!settingsObject.ContainsKey(t))
{
settingsObject.Add(t, defaultValue);
}
}
return settingsObject;
}