开发者

marking a WinForms Button as serializable

This is my very first program for serialization.

An error occurred when trying to serialize a button control.

public Form1()
{
     InitializeComponent();
     CheckSerialization();                
     Button btn = btnSerialized;            
}

public void CheckSerialization()
{
     Stream write = File.OpenWrite(@"C:\ser开发者_如何学Python.bin");
     BinaryFormatter serial = new BinaryFormatter();
     serial.Serialize(write, btnSerialized);
     write.Close();
}

private void btnSerialized_Click(object sender, EventArgs e)
{
     FileStream fs = new FileStream(@"C:\ser.bin",FileMode.Open);
     BinaryFormatter bf= new BinaryFormatter();
     object obj = bf.Deserialize(fs);
     Button button12 = (Button)obj;
     button1 = button12;
     button1.Location = new Point(0, 0);
}

Type 'System.Windows.Forms.Button' in Assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.**

How do I mark this object as serializable?


You don't. The type must be marked as Serializable, not the object.


Find the line that looks like public partial class Form1 : Form. Right above it, place [Serializable]. That marks your class for serialization. You will need to control your own serialization however, since as noted below, UI objects do not serialize. For that, look at the ISerializable interface.

More information about SerializableAttribute is here.


You can't serialize Winforms objects (or other UI objects, generally speaking)


IF you are trying to export the object or reload the object with user provided property values for dynamicity then why dont' you use System.Reflection. Here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜