代码之家  ›  专栏  ›  技术社区  ›  Shantanu Gupta

将WinForms按钮标记为可序列化

  •  1
  • Shantanu Gupta  · 技术社区  · 14 年前

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

    尝试序列化按钮控件时出错。

    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);
    }
    

    类型“system.windows.forms.button”in assembly“system.windows.forms,version=4.0.0.0,culture=neutral,publicKeyToken=b7a5c561934e089”未标记为可序列化。**

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

    4 回复  |  直到 11 年前
        1
  •  1
  •   Matthew Ferreira    14 年前

    找到看起来像 public partial class Form1 : Form . 就在上面,地方 [Serializable] . 将类标记为序列化。 但是,您需要控制自己的序列化,因为如下所述,UI对象不会序列化。为此,请看 ISerializable 接口。

    有关序列化属性的详细信息是 here .

        2
  •  2
  •   Fyodor Soikin    14 年前

    不可以。类型必须标记为可序列化,而不是对象。

        3
  •  0
  •   Ana Betts    14 年前

    您不能序列化WinForms对象(或其他UI对象,一般来说)

        4
  •  0
  •   user846493    11 年前

    如果您尝试导出对象或使用用户提供的动态属性值重新加载对象,那么为什么不使用System.Reflection。在这里: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime