我们的计划遇到了崩溃,我们现在无法重现。我试图放入一些代码来防止它再次发生,但我对堆栈跟踪感到困惑。
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Object.GetType()
at Project.ViewModel.MainVM.<CreateCommands>b__8(Object a)
at System.Windows.Controls.Button.OnClick()
- 我已经减少了堆栈跟踪,因为它只是进入一系列系统代码,这与点击的按钮有关。 -
我设法推断出它指向我的CreateCommands方法第8行的匿名委托。
this.sectionCommand = new DelegateCommand(a =>
{
this.OnSectionParameterChanged((Sections)a);
}, p => this.IsSectionCommandExecutable);
我在这里看过类似的帖子,但是OP明确地调用了GetType。我假设转换调用获取类型,但无法重现问题,我无法看到什么是null。
所以我的问题是:对于这个堆栈跟踪导致空引用,空对象的'a'变量是什么? (所以我会写类似的东西)
if (a != null)
{
this.OnSectionParameterChanged((Sections)a);
}
或是从'a'到'sections'的转换导致一个空对象? (所以我应该写点似的东西)
if (a is Sections)
{
this.OnSectionParameterChanged((Sections)a);
}
这里要求的是OnSectionParameterChanged
private void OnSectionParameterChanged(Sections parameter)
{
this.SelectedSection = parameter;
this.RaisePropertyChanged(() => this.SelectedSection);
this.LoadSettingsPanel();
}
进一步说它调用了LoadSettingsPanel
private void LoadSettingsPanel()
{
if (sectionVMs == null)
return;
// Get section
SectionViewModel = sectionVMs.SingleOrDefault(s.SectionName == SelectedSection);
this.IsSelectedSectionEnabled = this.Config.GetIsSectionEnabled(this.SelectedSection);
this.RaisePropertyChanged(() => this.IsSelectedSectionEnabled);
// Set advanced
AdvancedViewModel = this.SectionViewModel;
if (AdvancedViewModel != null)
HasAdvanced = AdvancedViewModel.HasAdvanced;
}
答案 0 :(得分:28)
我所描述的问题实际上并不是真正的问题。我在另一个网站上读到,堆栈跟踪的< CreateCommands >b__8
部分意味着问题出现在CreateCommands
方法的第8行。这与匿名代表完全排列,我可以看到它与错误报告中的行为相匹配。
我实际上通过使用IL Dasm找到了我的问题的解决方案(可以在
中找到)\ Program Files(x86)\ Microsoft SDKs \ Windows \ v7.0A \ Bin
打开运行的EXE,发现.net认为b__8
实际上是什么。结果是另一个匿名委托,它明确地调用了.GetType()
,所以一旦我发现b__8
实际意味着什么,这个问题实际上很容易。