【问题标题】:XmlSerialization and interfacesXmlSerialization 和接口
【发布时间】:2012-04-11 15:33:14
【问题描述】:

我知道您无法使用接口进行序列化/反序列化,但我对所看到的行为感到困惑。

当我反序列化并转换回接口时,一些属性为空。但是,如果我转换回具体类型,相同的属性是否有值?

因此,鉴于此 XML(为简洁而缩短):

<Page>
  <ComponentPresentations>
    <ComponentPresentation>
      <Component>
        <Categories>
          <Category>
            <Id>tcm:35-540-512</Id>

反序列化

var serializer = new XmlSerializer(typeof(Page));
page = (IPage)serializer.Deserialize(reader);

page.ComponentPresentations[0].Component.Categories <-- is null

但如果我回溯到类型,

var serializer = new XmlSerializer(typeof(Page));
page = (Page)serializer.Deserialize(reader);

page.ComponentPresentations[0].Component.Categories <-- is not null!

Page 类型公开了接口 Categories 属性和非接口属性 - 我假设可以解决序列化接口问题。

public List<Category> Categories { get; set; }
[XmlIgnore]
IList<ICategory> IComponent.Categories
{
    get { return Categories as IList<ICategory>; }
}

这是因为接口属性没有公开设置器吗?

【问题讨论】:

    标签: c# xml c#-4.0 serialization interface


    【解决方案1】:

    没有。问题是List&lt;T&gt;IList&lt;T&gt; 不支持逆变性Here 是一个很好的参考。


    看看这个简单的代码:

    public interface IMyInterface
    {
    
    }
    
    public class MyImplementation : IMyInterface
    {
    
    }
    
    List<MyImplementation> myImplementations = new List<MyImplementation>();
    Console.WriteLine(myImplementations as IList<IMyInterface> == null); // OUTPUT: true!!
    

    如您所见,Categories as IList&lt;ICategory&gt; 将始终为空。而Categories as IList&lt;Category&gt; 就可以了。

    与序列化无关

    【讨论】:

    • @Neil 使用 IEnumerable&lt;T&gt; 将为您提供所需的功能。
    猜你喜欢
    • 2010-11-27
    • 2011-11-28
    • 2011-07-24
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    相关资源
    最近更新 更多