对象与目标类型不匹配

本文关键字:不匹配 类型 目标 对象 | 更新日期: 2023-09-27 17:56:45

我有一个TableLayoutPanel,里面有一个PictureBox控件的网格。 我正在尝试找到一种将它们全部更改为标签控件的快捷方式,而不是手动删除每个控件并在每个单元格中放置新控件。

我以为我可以进入设计器代码并用标签查找/替换 PictureBox,但现在我得到了一个

"对象与目标类型不匹配"

Visual Studio 错误列表中的错误。 我现在也无法查看设计器页面。 这是不允许的吗? 如果允许,正确的方法是什么?

对象与目标类型不匹配

如果你仔细看看生成的代码:

label1

this.label1 = new System.Windows.Forms.Label();
// 
// label1
// 
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(134, 163);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 1;
this.label1.Text = "label1";

pictureBox1

this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
// 
// pictureBox1
// 
this.pictureBox1.Location = new System.Drawing.Point(97, 75);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(100, 50);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;

我的猜测是

((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();

被你改成这样的东西:

((System.ComponentModel.ISupportInitialize)(this.label1)).BeginInit();

这不起作用,并导致设计器问题。 Object does not match target type.

因此,应用您已经完成的更改,删除以下行:

((System.ComponentModel.ISupportInitialize)(this.label1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.label1)).EndInit();

我认为你很好。

不要更改设计器代码。 这些东西是自动生成的。 您的更改不仅会导致意外行为,而且还可能被覆盖。

我会尝试对您的表单或您的设计师背后的任何内容进行更改或 2 项更改,并希望它重新生成所有代码。

可以在设计器中删除所有图片框,然后在 _load 事件(或其他方便的事件)中添加所有标签。这样下次更改会更容易。

正如Haxx所示,您还必须清理PictureBox所需的额外初始化。您收到的错误是接口转换错误。在您的情况下,正如 Haxx 所猜测的那样,Label 控件不会实现 ISupportInitialize 接口。

与大多数人不同,我不怕为了权宜之计而更改设计器代码,对于您正在做的事情,这样做是可以的。只需了解您的对象,在这样做之前签入,并且不要将自定义代码放入其中!