简体   繁体   中英

Error serializing data in an xml file

I have a problem with the highscore code for a game I am creating in school.

When the game ends it says that it cant access HighScore because of its protection level.

This is the code that is giving me an error :

public static HighScore LoadHighScores(string filename)
{
        HighScore data;
        // Get the path of the save game
        string fullpath = "highscores.xml";

        // Open the file
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read);
        try
        {
            // Read the data from the file
            XmlSerializer serializer = new XmlSerializer(typeof(HighScore));
            data = (HighScore)serializer.Deserialize(stream);
        }
        finally
        {
            // Close the file
            stream.Close();
        }


        return (data);
}

When i run the code and die i call this code that saves the score i got:

public void SaveHighScore(int score)
{
        // Create the data to saved
        HighScore data = LoadHighScores(HighScoresFilename);
        int scoreIndex = -1;
        for (int i = data.Count--; i > -1; i--)
        {
            if (score >= data.Score[i]) //score.getScore();
            {
                scoreIndex = i;
            }
        }

        if (scoreIndex > -1)
        {
            //New high score found ... do swaps
            for (int i = data.Count--; i > scoreIndex; i--)
            {
                data.PlayerNames[i] = data.PlayerNames[i - 1];
                data.Score[i] = data.Score[i - 1];
            }

            data.PlayerNames[scoreIndex] = PlayerName; //Retrieve User Name Here
            data.Score[scoreIndex] = score; // Retrieve score here

            SaveHighScores(data, HighScoresFilename);
        }
}

And SaveHighScores looks like this:

public static void SaveHighScores(HighScore data, string filename)
{
        // Get the path of the save game
        string fullpath = "highscores.xml";

        // Open the file, creating it if necessary
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
        try
        {
            // Convert the object to XML data and put it in the stream
            XmlSerializer serializer = new XmlSerializer(typeof(HighScore));
            serializer.Serialize(stream, data);
        }
        finally
        {
            // Close the file
            stream.Close();
        }
}

Please check this link Public Class - "is inaccessible due to its protection level. Only public types can be processed."

you can find your answer there....

As a summary mark your HighScore as public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM