c# - XmlSerializer 不会序列化 IEnumerable

标签 c# xml-serialization xmlserializer

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

例如,void MethodWithPlace( Place value )会被序列化,但是 void MethodWithPlace( IEnumerable<Place> value )不会。

异常(exception)情况是

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

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

最佳答案

序列化 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; } }
}

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

关于c# - XmlSerializer 不会序列化 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9102234/

相关文章:

c# - 使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型

c# - 什么是好的Telnet 客户端实现C#?

c# - 带有验证器的 FileUpload 的附加 onchange 事件

c# - 流不可读错误

c# - .NET XmlSerializer 编译类型模式读取器/写入器

c#-4.0 - 通用 XML 序列化程序,但不适用于 JObject

c# - XmlSerializer 忽略公共(public)字段?

c# - 如何在 VS WPF 设计面板中显示集合数据?

c# - 如何在 GridView 的 CommandArgument 中传递多个参数?

c# - 当元素可能是许多可能元素之一时,将 XML 元素反序列化为对象