Why are System.Windows.Forms.Control not marked as

2019-01-28 12:07发布

I am not able to deep copy UserControls because they are not marked as serializable.

What is the reason behind this design?

3条回答
做自己的国王
2楼-- · 2019-01-28 12:34

You can serialize Controls but not via standard serializers. If you'd like serialize one or more control on a form to save the form design and/or other control properties you can use the same serialization used by visual studio (via CodeDomSerializer) but you need to implement several classes (I think at least IDesignerSerializationManager). You can see a sample here

http://support.microsoft.com/default.aspx?scid=kb;en-us;813808

The serialization is in Class SampleDesignerLoader method Flush.

In the same method there is also a serialization in an XML stream that does not use classes used by visual studio.

In the same class there is the deserialization from XML.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-28 12:39

Serializing a control isn't the problem, it is deserializing it that's incredibly hard to do right. The expectation is that this will produce an exact clone of the control. That's almost impossible to do accurately, there's an enormous amount of runtime state associated with a control. Not just in the Control class object itself, also in the internal state of the window, state that Windows doesn't allow you to directly access.

But the ultimate problem is that it has state that's associated with the process instance. Important internal properties like the Windows window class name and the secret property accessor keys are different from one run of the program to another. Recreating the control when it was serialized in a previous run of the program, or another program entirely, is thus not possible.

That said, the Winforms designer actually supports control serialization. Not into bytes, it generates code. Code that recreates the control at runtime, looking the same as it did at design time. Minus a whole bunch of details like size and colors, they often end up different on another machine. The big advantage that the designer has is that it only needs to serialize the initial state of the control, its state at constructor time. Doing the same at any point after this, after Windows has created the control's window and sent it a bunch of messages is a far tougher nut to crack. It is a bug factory. And thus not supported.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-28 12:51

Usercontrols are a visual element, and as such why would you ever want to serialize them? You are never going to send them across a WCF service, or stream them to a data repository. If you need to transmit or store usercontrols then you would store their key properties and recreate them where necessary.

Instead of using serialization to create a clone, go back to using a more traditional method like manually copying specific properties on known types, or use reflection.

查看更多
登录 后发表回答