class AppDataManager
{
public static async Task SaveAsync<T>(T data, string fileName)
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName,
CreationCollisionOption.ReplaceExisting);
var stream = await file.OpenStreamForWriteAsync();
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream ,data);
await stream.FlushAsync();
}
public static async Task<T> RestoreAsync<T>(string fileName)
{
try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
var instream = await file.OpenStreamForReadAsync();
var serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(instream);
}
catch (Exception)
{
return default(T);
}
}
}
在单击事件的 MainPage.XAML 中。
private async void SaveButton_Click_1(object sender, RoutedEventArgs e)
{
data = new UserData()
{
Name = "ibraheem",
ID = 1,
phoneNumber = 799,
Course = "java"
};
await AppDataManager.SaveAsync<UserData>(data, fileName);
}
当我单击“保存”按钮时,它给了我异常
无法序列化类型“DesigningElements.UserData”。考虑使用 DataContractAttribute 属性对其进行标记,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。如果该类型是一个集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。