Mystery System.Object.GetType() NullReferenceException
本文关键字:NullReferenceException GetType System Object Mystery | 更新日期: 2023-09-27 18:01:16
我们的程序出现了崩溃,现在无法恢复。我试图放入一些代码,以防止它再次发生,但我对堆栈跟踪感到困惑。
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()
——我已经减少了堆栈跟踪,因为它只是进入系统代码的负载,这只是与按钮被点击有关。——
我已经设法推断,它是指向我的匿名委托在第8行我的createcommand方法。
this.sectionCommand = new DelegateCommand(a =>
{
this.OnSectionParameterChanged((Sections)a);
}, p => this.IsSectionCommandExecutable);
我在这里看到过一个类似的帖子,但是OP显式地调用了GetType。我假设cast调用获得类型,但由于无法重现问题,我无法看到什么是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;
}
我所描述的问题实际上并不是真正的问题。我在另一个网站上看到,堆栈跟踪的< CreateCommands >b__8
部分意味着问题在CreateCommands
方法的第8行。这与匿名委托完全一致,我可以看到它是如何与bug报告中的行为相匹配的。
我实际上通过使用IL asm(可以在
中找到)找到了解决我的问题的方法。'Program Files (x86)'Microsoft sdk 'Windows'v7.0A'Bin
并打开运行的EXE,发现。net认为b__8
实际上是什么。这原来是另一个匿名委托,它显式地调用.GetType()
,所以一旦我发现b__8
的实际含义,问题实际上非常简单。