我正在上一个我从System.Windows.Forms.Control派生的课程
[Serializable]
public class CommonControl : System.Windows.Forms.Control,IXmlSerializable
{
这个类基本上为默认的Controls类添加了一些属性。 我的问题是我无法将Control对象强制转换为我的自定义控件对象。由于customcontrol类派生自Controls,我认为它可能有用。
我正在做这样的演员。
CommonControl ctrlTemp = new CommonControl();
ctrlTemp = (CommonControl)((Control)ctrl);
这里的ctrl是一个Label对象。当我调试第一次铸造工作正常。
(Control)ctrl
部分。但是当调试(CommonControl)((Control)ctrl)
时,它会显示以下消息。
(CommonControl)(ctrl)无法强制转换 'ctrl'(其实际类型为 'System.Windows.Forms.Label')来 'SharpFormEditorDemo.CommonControl'SharpFormEditorDemo.CommonControl
答案 0 :(得分:6)
您无法跨类层次结构进行转换。 Label
和CommonControl
都是从Control
继承的,但它们是不同的兄弟类,因此您不能将其中一个转换为另一个,甚至不能通过其父级转发。
或者更简单地说:一旦你创建了一个Label
对象,它总是一个Label
对象,即使你将它转换为Control
使用它。通过将其强制转换为CommonControl
,您将完全更改其类型,这在C#中是非法的。
也没有多重继承。作为一种变通方法,您可以创建一个接口,然后创建需要使用的控件的子类,这些控件都实现了自定义接口。一个快速而肮脏的例子:
public interface ICommonControl : System.Xml.Serialization.IXmlSerializable {
// ...
}
[Serializable]
public class MyLabel : System.Windows.Forms.Label, ICommonControl {
// Implement your common control interface and serializable methods here
}
然后将ctrl
创建为MyLabel
个对象。它继承自Label
并采用您的类定义的所有接口方法。如果您需要投射它,请将其投射到ICommonControl
。
是的,您需要为每个控件类创建子类,但这只是我能想到的一个解决方案。
答案 1 :(得分:1)
天啊,你知道你在做什么吗? ctrl是Label,绝对不是CommonControl和Control之间的层次结构。 您应该在CommonControl和Control层次结构之间将ctrl类型更改为用户定义类型,然后它将起作用。
将ctrl转换为Control绝对没问题,因为Label派生自Control。然而,将ctrl转换为CommonControl绝对是错误的,因为ctrl决不与CommonControl
有任何关系你可以做的是创建一个派生自Label的类,并使ctrl创建该类的对象。该类正在实现您想要的界面。