【问题标题】:Save interface type object to IsolatedStorageSettings, serialization将接口类型对象保存到IsolatedStorageSettings,序列化
【发布时间】:2014-12-20 14:22:56
【问题描述】:

我需要将实现 IAnimal 接口的列表对象存储到 Windows Phone 8 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”数据合约的数据。反序列化器不知道映射到该合约的任何类型。将与“Cat”对应的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将其添加到传递给 DataContractSerializer 的已知类型列表中。

我也尝试将 KnownType 属性添加到 Cat and Dog 但没有成功。

当我只知道对象实现了某个接口时,这是将对象存储到 IsolatedStorageSettings 的正确方法吗?

【问题讨论】:

    标签: c# windows-phone-8 serialization interface isolatedstorage


    【解决方案1】:

    我怀疑您将 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

    【讨论】:

    • 目前我没有任何基类(Animal),所有不同的动物都直接实现了IAnimal接口。但我会尝试像你解释的那样添加基类。
    • 您必须记住,接口只是类承诺实现的契约。当你序列化/反序列化时,你实际上是在序列化/反序列化一个类,而不是一个接口。
    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多