将WinForms Button标记为可序列化 [英] marking a WinForms Button as serializable

查看:107
本文介绍了将WinForms Button标记为可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个序列化程序.

尝试序列化按钮控件时发生错误.

 公共Form1(){InitializeComponent();CheckSerialization();按钮btn = btnSerialized;}公共无效CheckSerialization(){流写入= File.OpenWrite(@"C:\ ser.bin");BinaryFormatter serial =新的BinaryFormatter();serial.Serialize(write,btnSerialized);write.Close();}私有无效btnSerialized_Click(对象发送者,EventArgs e){FileStream fs = new FileStream(@"C:\ ser.bin",FileMode.Open);BinaryFormatter bf = new BinaryFormatter();对象obj = bf.Deserialize(fs);按钮button12 =(按钮)obj;button1 = button12;button1.Location =新Point(0,0);} 

程序集"System.Windows.Forms,版本= 4.0.0.0,文化=中性,PublicKeyToken = b77a5c561934e089"中的类型"System.Windows.Forms.Button"未标记为可序列化.**

如何将该对象标记为可序列化?

解决方案

查找类似于公共局部类Form1:Form 的行.在其上方,放置 [Serializable] .这将标记您的类进行序列化.但是,您将需要控制自己的序列化,因为如下所述,UI对象不会序列化.为此,请查看 ISerializable 接口

有关SerializableAttribute的更多信息,请此处.

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.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?

解决方案

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.

这篇关于将WinForms Button标记为可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆