Casting System.Windows.Forms.Label for custom type

I have a class where I get from System.Windows.Forms.Control

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

Basically this class adds a few more properties to the Controls class by default. My problem is that I cannot use Control objects in my custom control objects. Since the customcontrol class is derived from the controls, I thought this might work.

I do casting this way.

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

Here ctrl is the Label object. When I debug, the first castings work fine. (Control)ctrlpart. But when debugging (CommonControl)((Control)ctrl)displays the following message.

(CommonControl) (ctrl) Cannot execute 'ctrl' (which is of the actual type “System.Windows.Forms.Label”) on “SharpFormEditorDemo.CommonControl” SharpFormEditorDemo.CommonControl

+3
source share
2 answers

You cannot use class hierarchies. Labeland CommonControlboth inherit from Control, but are separate sibling classes, and therefore you cannot drop them to each other, not even through your parents.

Or simpler: just by creating an object Label, it will always be an object Label, even if you use it to use it as Control. By dropping it on CommonControl, you completely change your type, which is illegal in 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.

, , , .

+6

, , , ? ctrl - , CommonControl Control. ctrl CommonControl , .

ctrl to Control , Label Control. ctrl CommonControl , ctrl CommonControl

, , Label, ctrl . .

+1

Source: https://habr.com/ru/post/1779933/


All Articles