简体   繁体   中英

Serialization does not work with multiple projects

I'm creating a game for the windows phone with the xna framework. I want to store my levels in an xml file so i thought i'll be using xmlserialization and deserialization. I've first created a test project to see if this would work and it does no problems there.

Now I've created a level editor and it's an windows forms application which i use to build the levels than i want to serialize them and in a different project (Windows Phone) deserialize it. In order to keep the objects the same i've referenced the windows phone application in the windows forms application. I've used the same references for the serialization.

using System.Xml.Serialization;

But when i try to serialize the object i get an exception: There was an error reflecting type .

So my question is why can't i serialize objects from a different project? Or is this just not possible?

public static void SaveLevel(Level level)
{
   FileStream fs = new FileStream(@"c:\level1.xml", FileMode.Create);

   MemoryStream ms = new MemoryStream();
   Serialize(ms, level);

   fs.Write(ms.ToArray(), 0, (int)ms.Length);

   ms.Close();
   fs.Close();

   ms.Dispose();
   fs.Dispose();
}

public static void Serialize(Stream streamObject, object objectForSerialization)
{
   if (objectForSerialization == null || streamObject == null)
        return;

   XmlSerializer serializer = new XmlSerializer(objectForSerialization.GetType()); //error occurs
   serializer.Serialize(streamObject, objectForSerialization);
}

Object that needs to be serialized.

public class Level
{
    [XmlElement]
    public string Name { get; set; }

    public Level()
    {
    }
}

Once i've copied the file to the levelEditor project it will serialize and deserialize it. But i actually don't want to copy those files because if i change a file in one project i also need to change it in the other project which isn't very handy.

As far as i knew, to serialize a custom type, you have to give the class a [Serializable] attribute. like this.

[Serializable]
public class Level
{

    //......
}

see if that solves it.

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