我知道您不能使用接口进行序列化/反序列化,但是我对所看到的行为感到困惑。
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和接口
发布评论