我正在制作一个UWP应用程序,我试图通过序列化将用户选择的存储文件保存到本地设置,我想反序列化它们并在我想要的时候再次使用它们 . 它将IReadOnlyList对象保存到本地设置就好了,但在反序列化它给出和异常时,这个方法无法返回存储文件,因为它没有这样的构造函数,就像这样 . 我发布了保存和加载数据的两种方法的代码 . 请看看并帮助我......
public static void SaveState<T>(string key, T value)//save method
{
//key is provided by me so that i can use it to load the data later.
var localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values[key] = JsonConvert.SerializeObject(value);
}
public static T LoadState<T>(string key)//loading data
{
var localSettings = ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey(key))//exception occurs on the below line
return JsonConvert.DeserializeObject<T>(((string)localSettings.Values[key]));
return default(T);
}
我使用这些方法如下: -
var files = StateService.LoadState<IReadOnlyList<StorageFile>>(Playlist);
//StateService is the class which has these static methods...
注意:当我尝试使用在本地设置中没有数据的密钥加载数据时,它不会给出任何异常,只返回一个空列表 . 但是当它应该返回一个填充的IReadOnlyList列表时,它会给出异常...
2 回答
我认为
JsonConvert.DeserializeObject
试图实例化IReadOnlyList<StorageFile>
但接口无法实例化...你应该使用例如List<StorageFile>
作为T来设置和读取列表...之前我做过类似的事情,但我遇到了同样的问题 . 我做了不同的方法而不是尝试保存StorageFile我用密钥保存了json内容,并且我的数据总是在字符串(json数据)中,我可以毫无问题地使用
JsonConvert.DeserializeObject<T>
.