XmlSerialization和接口 [英] XmlSerialization and interfaces

查看:52
本文介绍了XmlSerialization和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that you can't serialize/deserialize using an interface but I'm confused by behaviour I'm seeing.

当我反序列化并转换为接口,某些属性为null。但是,如果我将其转换回具体类型,则同一个属性是否具有值?

When I deserialize and cast back to the interface, some properties are null. But if I cast back to the concrete type the same property has a value?

因此,鉴于此XML(为简洁起见,其缩写为:):

So, given this XML (shortened for brevity):

<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

但是如果我强制转换回类型,

But if I cast back to the type,

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

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

Page类型公开了接口Categories属性和非接口属性-我想避开

The Page type exposes the interface Categories property and a non-interface property - I assume to get around the serializing interface problem.

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

这是因为interface属性没有公开setter吗?

Is this because the interface property doesn't expose a setter?

推荐答案

否。问题是 Contravariance 不受 List< T> IList< T> 的支持。 此处是一个很好的参考。

No. The problem is Contravariance not being supported by List<T> and IList<T>. Here is a good reference.

看看这个简单的代码:

public interface IMyInterface
{

}

public class MyImplementation : IMyInterface
{

}

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

如您所见,类别为IList< ICategory> 将始终为null。尽管类别为IList< Category> 可以。

So as you can see, Categories as IList<ICategory> will always be null. While Categories as IList<Category> will be OK.

与序列化无关 >。

这篇关于XmlSerialization和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆