簡體   English   中英

將接口類型對象保存到IsolatedStorageSettings中,進行序列化

[英]Save interface type object to IsolatedStorageSettings, serialization

我需要存儲實現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數據合同。 解串器不知道任何映射到該合同的類型。 將與“貓”相對應的類型添加到已知類型的列表中-例如,通過使用KnownTypeAttribute屬性或將其添加到傳遞給DataContractSerializer的已知類型的列表中。

我也曾嘗試將KnownType屬性添加到Cat and Dog,但是沒有成功。

當我僅知道對象實現某些接口時,這是將對象存儲到IsolatedStorageSettings的正確方法嗎?

我懷疑您將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/zh-CN/library/ms751512(v=vs.110).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM