【问题标题】:Serialization Exception序列化异常
【发布时间】:2011-03-22 14:57:33
【问题描述】:

我正在尝试保存国际象棋游戏的状态。

private void saveToolStripMenuItem_Click(object sender, EventArgs e)// menu strip control
{
    saveFileDialog1.InitialDirectory = @"c:\";

    DialogResult result= saveFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        saveToFile(saveFileDialog1.FileName);
    }

}

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
    openFileDialog1.InitialDirectory = @"c:\";

    DialogResult result= openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        openFile(openFileDialog1.FileName);
    }
}
GameSave game2 = new GameSave();
public void saveToFile(string s)
{
    game2.setLoadedPieces(codeFile.PieceState());// will pass the current pieces state. that is an array of all the chess pieces objects..which determine where each piece is on the board
    FileStream f = new FileStream(s, FileMode.Create);
    BinaryFormatter b = new BinaryFormatter();

    b.Serialize(f, game2);// throws here an exception.Type 'WindowsFormsApplication1.Pieces' in Assembly 'ChessBoardGame, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
    f.Close();
}

public void openFile(string s)
{
    FileStream f = new FileStream(s, FileMode.Open);// will open the file and the stream
    BinaryFormatter b = new BinaryFormatter();
    game2 = (GameSave)b.Deserialize(f);// will load the stream
    f.Close();
    codeFile.setPieces(game2.getLoadedPieces());// sets the board to the loaded pieces.
    PrintPieces(game2.getLoadedPieces());//prints the existing loaded pieces.
}


[Serializable] 
class GameSave
{
    Pieces[,] pieces;


    public void setLoadedPieces(Pieces[,] serializedSavedPieces) // set the pieces array  to be saved
    {       
        this.pieces = serializedSavedPieces; 
    }
    public Pieces[,] getLoadedPieces() // returns the pieces array
    {
        return pieces;
    }

}

异常类型:

程序集“ChessBoardGame, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“WindowsFormsApplication1.Pieces”未标记为可序列化。

【问题讨论】:

  • 你好,德米特里。一旦一个满意的答案,StackOverflow 习惯上会接受答案(通过单击复选标记)。您已经提出了 14 个问题(包括这个问题),但只接受了一个。如果您继续,有些人可能会拒绝帮助您。请阅读常见问题解答了解更多信息。
  • 我昨天给了接受打勾,今天我给了
  • 谢谢。不要忘记你过去的问题。它们也很重要。

标签: c# winforms serialization


【解决方案1】:

也许您应该将 WindowsFormsApplication1.Pieces 标记为 [Serializable] ? :)

【讨论】:

  • 它不会让我使命名空间可序列化。我有一个静态数组 Pieces 类型,它在一个类中,我将属性序列化放在上面,
  • 没关系,现在可以了。我必须将可序列化属性放在我拥有的几个类之上,现在它可以工作了!!!
猜你喜欢
  • 2014-04-18
  • 2010-12-15
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多