保存IsolatedStorage时出现InvalidDataContractException错误
本文关键字:InvalidDataContractException 错误 IsolatedStorage 保存 | 更新日期: 2023-09-27 18:03:46
我正在VS2012 中为Windows Phone 8.0开发一个应用程序
并且我在SetProfile.xaml页面中有一个IsolatedStorage
SetProfile.xaml
public partial class SetProfile : PhoneApplicationPage
{
private int Indexer;
private int age;
IsolatedStorageSettings Profile = IsolatedStorageSettings.ApplicationSettings;
private void create_Click(object sender, RoutedEventArgs e)
{
if (FirstName.Text != "" && LastName.Text != "" && Age.Text!= "")
{
age = Convert.ToInt32(Age.Text);
//catch (FormatException exc) { };
if (age > 5 || age < 120)
{
Player player = new Player();
player.FirstName = FirstName.Text;
player.LastName = LastName.Text;
try
{
player.Age = Convert.ToInt32(Age.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Age");
Age.Text = "";
return;
}
player.Rank = 1;
player.RankDescreption = "Beginner";
player.Points = 0;
Indexer = GetCurrentIndex();
string key = string.Format("player{0}", Indexer);
if (Indexer == 1)
{
player.ID = Indexer;
Profile.Add("CurrentProfile", player);
Profile.Add("PlayersCount",(int)1);
}
else
Profile["CurrentProfile"] = player;
player.ID = Indexer;
Profile.Add(key, player);
int count = (int)Profile["PlayersCount"];
count++;
Profile["PlayersCount"] = count;
Profile.Save();
NavigationService.Navigate(new Uri("/Avatars.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Age is Invalid");
create_Click(null, null);
}
}
}
当我调试应用程序时,它在Profile.Save();
行崩溃带'System.Runtime.Serialization.InvalidDataContractException'
我不知道为什么会发生这种情况,我已经在我的应用程序上工作了很长时间,代码也在工作,但今天当我向项目中添加一个类(Game
((与Player类相关(时,这个错误开始出现
关于我添加的类的更多信息:在我不久前发布的这个问题中:向列表添加项目时出现AccessViolationExceptionInvalidDataContractException意味着您需要使用[DataContractAttribute]
属性标记正在序列化的内容。
随后,您还需要用[DataMember]
标记对象的任何成员,以便序列化程序识别它
好消息是,如果您想要一种更简单的方法将对象序列化到我已经构建的隔离存储中,并且它是免费的。它被称为EZ_iso.dll,我已经在堆栈交换上发布了很多次,它已经被新的和经验丰富的开发人员广泛采用。
就是一个例子
[DataContractAttribute]
public class MainPageSettings
{
[DataMember]
publicString yourSetting1 {get; set;}
[DataMember]
public List<Object> yourSetting2 {get; set;}
[DataMember]
public int yourSetting3 {get; set;}
[DataMember]
public Boolean yourSetting4 {get; set;}
}
现在你可以保存你的数据,并用一行代码检索它
序列化(在初始化后(
EZ_Iso.IsolatedStorageAccess.SaveFile("MPageSettings",yourSettingsObj);
然后去反序列化它
MainPageSettings yourSettingsObj = (MainPageSettings)EZ_Iso.IsolatedStorageAccess.GetFile("MPageSettings",typeof(MainPageSettings));
就这么简单。
您可以在这里找到EZ_Iso