2011-03-22 124 views
0

我試圖保存一個國際象棋遊戲。例外的序列化異常

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

} 

類型:在大會

類型「WindowsFormsApplication1.Pieces 'ChessBoardGame,版本= 1.0.0.0,文化=中立,公鑰=空' 未標記爲可序列。

+1

你好德米特里。一旦滿意,StackOverflow通常會接受答案(通過點擊複選標記)。你問了14個問題(包括這個問題),但只接受了一個問題。如果你繼續,有些人可能會拒絕幫助你。請閱讀常見問題了解更多信息。 – MPelletier 2011-03-22 15:02:00

+0

我昨天給了驗收,我今天會給 – 2011-03-22 15:17:38

+0

謝謝。不要忘記你過去的問題。他們也很重要。 – MPelletier 2011-03-22 15:41:40

回答

7

也許你應該將WindowsFormsApplication1.Pieces標記爲[Serializable]? :)

+2

+1因爲你添加了笑臉;) – jgauffin 2011-03-22 15:11:55

+0

它不會讓我使namesepace serliazable。我有一個靜態數組Pieces類型,這是在一個類,我把屬性序列化上面, – 2011-03-22 15:24:01

+0

沒關係,現在它的作品。我不得不把可序列化的屬性放在我有的幾個類上面,現在它可以工作了! – 2011-03-22 15:29:48