0
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 文档。

4

1 回答 1

2

确保你的UserData类声明类似于下面

[DataContract]
public class UserData
{
    [DataMember]
    public string Name { set; get; }
    [DataMember]
    public int ID { set; get; }
    [DataMember]
    public string phoneNumber { set; get; }
    [DataMember]
    public string Course { set; get; }
}
于 2013-01-17T18:32:05.373 回答