将System.Windows.Forms.Label转换为自定义类型

时间:2010-12-13 05:38:51

标签: c# winforms casting

我正在上一个我从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

2 个答案:

答案 0 :(得分:6)

您无法跨类层次结构进行转换。 LabelCommonControl都是从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创建该类的对象。该类正在实现您想要的界面。

相关问题