加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:39:44 所属栏目:百科 来源:网络整理
导读:我有一个类,我从System. Windows.Forms.Control派生 [Serializable] public class CommonControl : System.Windows.Forms.Control,IXmlSerializable { 基本上这个类为默认的Controls类添加了一些属性. 我的问题是我无法将Control对象强制转换为我的自定义控
我有一个类,我从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对象.当我调试第一次铸造工作正常.
(控制)ctrl部分.但是当调试(CommonControl)((Control)ctrl)时,它会显示以下消息.

(CommonControl)(ctrl) Cannot cast
‘ctrl’ (which has an actual type of
‘System.Windows.Forms.Label’) to
‘SharpFormEditorDemo.CommonControl’ SharpFormEditorDemo.CommonControl

解决方法

您不能跨类层次结构进行转换. 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.

是的,您需要为每个控件类创建子类,但这只是我能想到的一个解决方案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读