XmlSerializer不会序列化IEnumerable [英] XmlSerializer won't serialize IEnumerable

查看:58
本文介绍了XmlSerializer不会序列化IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用记录器,该记录器旨在使用XmlSerializer记录所有方法调用以及与该方法关联的参数。对于大多数调用来说,它工作得很好,但是对于参数 IEnumerable 类型的所有方法,它都会引发异常。

I have an invocation logger that is intended to record all method calls along with the parameters associated with the method using XmlSerializer. It works well for most of the calls, but it throws an exception for all methods that has a parameter of IEnumerable type.

例如,将对 void MethodWithPlace(放置值)进行序列化,但是 void MethodWithPlace(IEnumerable< Place>值)不会。

For example, void MethodWithPlace( Place value ) would be serialized, but void MethodWithPlace( IEnumerable<Place> value ) would not.

例外是


System.NotSupportedException:无法序列化接口
System.Collections.Generic.IEnumerable`1 [[Place,
Test,Version = 0.0.0.0,Culture = neutral]]。

System.NotSupportedException: Cannot serialize interface System.Collections.Generic.IEnumerable`1[[Place, Test, Version=0.0.0.0, Culture=neutral]].

我应该怎么做才能使其与以 IEnumerable 作为其参数之一的那些方法一起工作?

What should I do to make it work with those methods with IEnumerable as one of its parameters?

推荐答案

序列化IEnumerable属性的方式是使用代理属性

The way you serialize an IEnumerable property is with a surrogate property

[XmlRoot]
public class Entity {
   [XmlIgnore]
   public IEnumerable<Foo> Foo { get; set; }

   [XmlElement, Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
   public List<Foo> FooSurrogate { get { return Foo.ToList(); } set { Foo = value; } }
}

虽然丑陋,但却能完成工作。更好的解决方案是编写一个代理类(即EntitySurrogate)。

It's ugly, but it gets the job done. The nicer solution is to write a surrogate class (i.e. EntitySurrogate).

这篇关于XmlSerializer不会序列化IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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