我需要存储列表对象,它实现了Windows 8 IsolatedStorageSettings.ApplicationSettings的IsolatedStorageSettings.ApplicationSettings接口。
我的动物界面是这样的:
public interface IAnimal
{
string Name { get; }
}
然后,我有不同的动物,我想储存到IsolatedStorageSettings.ApplicationSettings。
public class Cat : IAnimal
{
string Name { get; set; }
}
public class Dog: IAnimal
{
string Name { get; set; }
}
我有办法获取/设置动物名单。
public IReadOnlyCollection<IAnimal> GetAnimals()
{
return (List<IAnimal>)storage["animals"];
}
public void AddAnimal(IAnimal animal)
{
List<IAnimal> animals = (List<IAnimal>)storage["animals"];
animals.Insert(0, (IAnimal)animal);
this.storage["animals"] = animals;
this.storage.Save();
}
如果我使用这些方法,我将得到System.Runtime.Serialization.SerializationException,元素'http://schemas.microsoft.com/2003/10/Serialization/Arrays:anyType‘包含'http://schemas.datacontract.org/2004/07/MyApp.Models:Cat’数据契约的数据。反序列化器不知道映射到本合同的任何类型。将与“猫”对应的类型添加到已知类型列表中,例如,使用KnownTypeAttribute属性或将其添加到传递给DataContractSerializer的已知类型列表中。
我还尝试向猫和狗添加KnownType属性,但没有成功。
当我只知道对象实现了某些接口时,这是将对象存储到IsolatedStorageSettings的正确方法吗?
发布于 2014-10-24 17:54:06
我怀疑您将KnownType属性放置在错误的位置。当我使用它时,我总是将它添加到基类中。
示例:
public interface IAnimal
{
string Name { get; }
}
[KnownType(typeof(Cat))]
[KnownType(typeof(Dog))]
public class Animal: IAnimal
{
string Name { get; }
}
public class Cat : Animal
{
string Name { get; set; }
}
public class Dog: Animal
{
string Name { get; set; }
}
http://msdn.microsoft.com/en-us/library/ms751512(v=vs.110).aspx
https://stackoverflow.com/questions/26553131
复制相似问题