XmlSerializer不会序列化IEnumerable

uni*_*uni 38 c# xml-serialization xmlserializer

我有一个调用记录器,用于记录所有方法调用以及与使用XmlSerializer的方法相关的参数.它适用于大多数调用,但它会为具有IEnumerable类型参数的所有方法抛出异常.

例如,void MethodWithPlace( Place value )将序列化,但void MethodWithPlace( IEnumerable<Place> value )不会.

例外是

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

我应该怎么做才能使用这些方法IEnumerable作为其参数之一?

Her*_*eld 31

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

[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; } }
}
Run Code Online (Sandbox Code Playgroud)

这很丑陋,但它完成了工作.更好的解决方案是编写代理类(即EntitySurrogate).


Kyl*_*e W 11

基本上,XmlSerializer无法序列化接口.然后,解决方案是给它一个序列化的具体实例.根据您的调用记录器的工作方式,我会考虑使用

var serializer = new XmlSerializer(value.GetType());
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 8

我不认为你能够序列化它.尝试将IEnumerable转换为List,然后您就可以序列化了.

  • 由于我无法更改方法签名,是否有任何解决方法可以解决此问题? (2认同)
  • 如果您只是将.ToList()添加到该方法签名,或者我应该让它返回IEnumberable.ToList() (2认同)
  • 你可以使用不同的序列化器,比如NetDataContractSerializer吗?您将无法使用XML序列化程序执行此操作. (2认同)