gpt4 book ai didi

c# - 带有 winforms 和 C# 的 this.Controls.Add() 上的 System.NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:47 25 4
gpt4 key购买 nike

我用 C# 开发了一个小型 WinForm 应用程序。我已经发布这个应用程序很多年了,很多用户在许多不同的 Windows 系统上使用它,Windows XP、Vista、7、8、32 位和 64 位。

但几天前,一位用户报告在 Windows 7 64 位机器上启动应用程序时发生崩溃。因为我这边无法重现错误,所以我把可以输出日志信息的debug版本发给他。

现在我找到了失败的行

this.Controls.Add(this.myUserControl);

这是 Visual Studio 从 Forms Designer 生成的一行。 “this.myUserControl”是用户控件的一个实例。此用户控件是在此项目中构建的,不包含任何外部组件。只是用一些标准的 UI 控件构建的。.NET错误信息为

"System.NullReferenceException: Object reference not set to an instance of an object."

我添加了代码来测试 this.myUserControl 在将其添加到控件之前是否为 null,它绝对不是 null。

我尝试了很多方法,比如使用corflags.exe强制运行在32位模式或者将构建目标框架更改为3.5(在2.0之前)

没有任何变化。它总是在那条线上崩溃。

在发布之前,我已经在 Windows 7 64bit 上测试了这个应用程序,并且这个应用程序有很多用户在 Windows 7 64bit 上使用它。所以我认为我不应该更改任何代码。但我对如何解决这个问题没有任何方向。

我应该告诉用户重新安装 Windows 还是修复 .Net Framework?有人在 Windows 7 64 位上遇到过这个错误吗?

英语不是我的母语,所以对不起我的英语。


与用户控件相关的代码,所有这些代码都是从 Forms Designer 生成的:

private MyUserControl myUserControl;

this.myUserControl = new ProjectNameSpace.MyUserControl();
this.myUserControl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.myUserControl.Location = new System.Drawing.Point(12, 80);
this.myUserControl.Name = "myUserControl";
this.myUserControl.Size = new System.Drawing.Size(775, 412);
this.myUserControl.TabIndex = 2;
this.myUserControl.Resize += new System.EventHandler(this.myUserControl_Resize);

this.Controls.Add(this.myUserControl);

最佳答案

如您所述,this.myUserControl 不为空;所以 this.Controls 可能是问题所在。检查 System.ComponentModel.IContainer 组件InitializeComponent();可能缺少或未初始化的东西。

Override OnLayoutOnPaint 有助于调试,IsHandleCreated 也可能是找出异常的关键点。

最简单的方法是使用设计器创建一个新的用户控件,然后粘贴您为业务编写的代码。请记住将控件命名为与原始控件相同。

关于c# - 带有 winforms 和 C# 的 this.Controls.Add() 上的 System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com