我需要保存一個對象列表,這些對象是從我創建的類創建的。我該怎麼辦?在Windows Phone 7中保存對象列表XNA
我試過XmlSerializer,並且我將[XmlElement]添加到需要序列化的字段中。但它一直給我「XML文檔中存在錯誤」。 我也試過DataContractSerializer,並且使用了[DataContract]和[DataMember],但它不會保存我的對象。
這兩個存儲類都適用於基本元素(int,bool ..等),但不適用於我的對象。
我的繼承人保存代碼:
using (IsolatedStorageFile saveGameFile = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream SaveGameStream = new IsolatedStorageFileStream("GemsCollector1.dat", FileMode.OpenOrCreate, saveGameFile))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Card>));
serializer.Serialize(SaveGameStream, Cards);
}
,這一次加載:
using (IsolatedStorageFile saveGameFile = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream saveGameStream = new IsolatedStorageFileStream("GemsCollector1.dat", FileMode.OpenOrCreate, saveGameFile))
{
if (saveGameStream.Length > 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Card>));
Cards = (List<Card>)serializer.Deserialize(saveGameStream);
}
}
我的卡類:
public class Card
{
[XmlElement]
public CardType CardType { get; set; }
[XmlElement]
public CardColor CardColor { get; set; }
[XmlElement]
public int Value { get; set; }
[XmlElement]
public Vector2 Position { get; set; }
[XmlElement]
public PlayerPosition playerPosition { get; set; }
[XmlElement]
public CardStatus Status { get; set; }
public Rectangle BoundingBox
{
get
{
int width = (playerPosition == PlayerPosition.Left || playerPosition == PlayerPosition.Right) ? 150 : 100;
int height = (playerPosition == PlayerPosition.Left || playerPosition == PlayerPosition.Right) ? 100 : 150;
return new Rectangle((int)Position.X, (int)Position.Y, width, height); ;
}
}
[XmlElement]
public bool isUsed;
public Vector2 endPosition = new Vector2(235,200);
public Rectangle ThrowArea = new Rectangle(235, 200, 350, 120);
[XmlElement]
public string cardTextureName;
private string back = "back";
private static bool ReserveDrag;
[XmlElement]
private Vector2 touchFromCenter;
[XmlElement]
private int touchId;
public Card()
{
}
}
有誰能夠告訴我,我們如何保存列表XNA中的用戶定義對象?
您是否試圖將其保存到手機的IsolatedStorage?如果是這樣,你應該發佈你的序列化代碼。 –
是的,到IsolatedStroage,我只是添加了我的代碼 – Ateik
正確,所以錯誤與您試圖序列化的「卡」對象有關。我想我們可以放心地假設你沒有讓類屬性可序列化。所以你也必須在這裏發佈卡類。 –