首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将接口类型对象保存到IsolatedStorageSettings,序列化

将接口类型对象保存到IsolatedStorageSettings,序列化
EN

Stack Overflow用户
提问于 2014-10-24 17:26:36
回答 1查看 172关注 0票数 0

我需要存储列表对象,它实现了Windows 8 IsolatedStorageSettings.ApplicationSettings的IsolatedStorageSettings.ApplicationSettings接口。

我的动物界面是这样的:

代码语言:javascript
运行
复制
public interface IAnimal
{
    string Name { get; }
}

然后,我有不同的动物,我想储存到IsolatedStorageSettings.ApplicationSettings。

代码语言:javascript
运行
复制
public class Cat : IAnimal
{
    string Name { get; set; }
}


public class Dog: IAnimal
{
    string Name { get; set; }
}

我有办法获取/设置动物名单。

代码语言:javascript
运行
复制
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的正确方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-24 17:54:06

我怀疑您将KnownType属性放置在错误的位置。当我使用它时,我总是将它添加到基类中。

示例:

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26553131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档