我想使用ToolStripMenuItem
函数将字符串强制转换为DirectCast
。我的代码是:
Dim ParentMenu As ToolStripMenuItem =
DirectCast(ComboBox1.SelectedItem, ToolStripMenuItem)
但它引发了以下错误
无法将“System.String”类型的对象强制转换为类型 'System.Windows.Forms.ToolStripMenuItem'。
答案 0 :(得分:4)
您不能将String强制转换为ToolStripMenuItem,因为String 不是 ToolStripMenuItem的简单事实! DirectCast函数需要两个对象之间的某种关系(如继承)才能工作。这意味着两个对象中的一个必须与另一个对象相同,或者其中一个必须继承或实现另一个。
详细了解DirectCast:https://msdn.microsoft.com/en-us/library/7k6y2h6x.aspx
如果您希望在一行中完成,请执行以下操作:
Dim ParentMenu As New ToolStripMenuItem(ComboBox1.SelectedItem.ToString())
您还需要使用.ToString()
或CStr()
,因为ComboBox1.SelectedItem作为对象返回。