XmlSerialization和接口

编程入门 行业动态 更新时间:2024-10-24 22:25:04
本文介绍了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和接口

本文发布于:2023-11-04 05:38:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   XmlSerialization

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!