我有一个调用记录器,用于记录所有方法调用以及与使用 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/