我们的程序发生崩溃,现在无法重现。我试图输入一些代码以防止它再次发生,但我对堆栈跟踪感到困惑。
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 行的匿名委托(delegate)。
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;
}
最佳答案
我所描述的问题实际上并不是真正的问题。我在另一个网站上读到 < CreateCommands >b__8
堆栈跟踪的一部分意味着问题出在 CreateCommands
的第 8 行方法。这与匿名委托(delegate)完全一致,我可以看到它如何与错误报告中的行为相匹配。
我实际上通过使用 IL Dasm 找到了我的问题的解决方案(可以在
\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin
并打开运行的 EXE,发现 .net 的想法 b__8
实际上是。这原来是另一个匿名委托(delegate),它明确调用了 .GetType()
所以一旦我发现了 b__8
的内容,问题实际上就很简单了实际上的意思。
关于c# - 神秘的 System.Object.GetType() NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246652/