将新的System.Windows.Forms.Control对象转换为System.Windows.Forms.Textbox

我将Control转换为System.Windows.Forms.Textbox时出现InvalidArgumentException:

无法将类型为“System.Windows.Forms.Control”的对象强制转换为“System.Windows.Forms.TextBox”。

System.Windows.Forms.Control control = new System.Windows.Forms.Control(); control.Width = currentField.Width; //here comes the error ((System.Windows.Forms.TextBox)control).Text = currentField.Name; 

我这样做,因为我有不同的控件(Textbox,MaskedTextbox,Datetimepicker …),它将动态添加到面板并具有相同的基本属性(大小,位置… – >控制)

为什么演员不可能?

转换失败,因为control 不是TextBox 。 您可以将TextBox视为控件(在类型层次结构的较高位置),但不能将任何Control视为TextBox 。 要设置公共属性,您可以将所有内容视为Control并设置它们,而您必须事先创建要使用的实际控件:

 TextBox tb = new TextBox(); tb.Text = currentField.Name; Control c = (Control)tb; // this works because every TextBox is also a Control // but not every Control is a TextBox, especially not // if you *explicitly* make it *not* a TextBox c.Width = currentField.Width; 

您控制的是Control类的对象,它是父类。 可能是更多的控件inheritance自父级。

因此,孩子可以作为父母而不是反之亦然。

而是使用它

 if (control is System.Windows.Forms.TextBox) (control as System.Windows.Forms.TextBox).Text = currentField.Name; 

要么

创建一个TextBox对象。 那个将永远是一个TextBox,你不需要检查/转换它。

乔伊是对的:

你的控件不是文本框! 您可以使用以下方法测试类

 System.Windows.Forms.Control control = new System.Windows.Forms.Control(); control.Width = currentField.Width; if (control is TextBox) { //here comes the error ((System.Windows.Forms.TextBox)control).Text = currentField.Name; } 

所有控件都从System.Windows.Forms.Controlinheritance。 但是,TextBox与DateTimePicker不同,因此您不能将它们相互转换,只能转换为父类型。 这是有道理的,因为每个控件都专门用于执行某些任务。

鉴于您拥有不同类型的控件,您可能希望首先测试类型:

 if(control is System.Windows.Forms.TextBox) { ((System.Windows.Forms.TextBox)control).Text = currentField.Name; } 

您还可以使用’ as ‘关键字推测性地转换为该类型:

 TextBox isThisReallyATextBox = control as TextBox; if(isThisReallATextBox != null) { //it is really a textbox! }