开发者

Casting System.Windows.Forms.Label to a custom type

I'm having a class where I'm deriving from System.Windows.Forms.Control

[Serializable]  
public class CommonControl : System.Windows.Forms.Control,IXmlSerializable 
{

Basically this class adds some more properties to the default Controls class. My problem is I cannot cast the Control objects into my custom control objects. Since the customcontrol class is derived from Controls I thought it m开发者_开发百科ight work.

I'm doing the casting like this.

CommonControl ctrlTemp = new CommonControl();
ctrlTemp = (CommonControl)((Control)ctrl);

Here the ctrl is a Label object. When I debug the first casting works fine. (Control)ctrl part. But when the (CommonControl)((Control)ctrl) is debugged it displays following message.

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


You cannot cast across class hierarchies. Label and CommonControl both inherit from Control but are distinct sibling classes, and thus you cannot cast one to the other, not even through their parent.

Or to put it more simply: once you create a Label object, it's always a Label object even if you cast it to use it as a Control. By casting it to CommonControl you're changing its type completely, which is illegal in C#.

There is no multiple inheritance either. As a workaround, you can make an interface, then create subclasses of the controls that you need to use that all implement your custom interface. A quick and dirty example:

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
}

Then creating ctrl as a MyLabel object. It inherits from Label and adopts all the interface methods defined by your class. If you need to cast it, cast it to an ICommonControl.

Yes, you need to subclass each control class, but it's just one solution I can think of.


Oh God, do you know what you are doing? ctrl is Label and definitely it is not in hierarcy between CommonControl and Control. You should change ctrl type to your user define type in between CommonControl and Control hierarchy, then it will work.

Casting ctrl to Control is definitely okay, since Label derived from Control. However casting ctrl to CommonControl is definitely wrong, since ctrl by no means have any relationship with CommonControl

What you can do is create a class derived from Label, and make ctrl to create an object of that class. And that class is implementing the interface you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜