![xml序列化与反序列化](https://i-blog.csdnimg.cn/blog_migrate/f98a4997a1cf4ffc6b7e7c364ddc8305.png)
xml序列化与反序列化
There's lots of good techniques out there for using the XmlSerializer to serialize a Generic List<> type. You can implement IXmlSerializable and some other trickiness.
使用XmlSerializer序列化Generic List <>类型有很多好的技术。 您可以实现IXmlSerializable和其他一些技巧。
Here's the simplest possible thing I could do to make it work while working on a hobby project over lunch today with a friend.
这是我今天与朋友共进午餐时从事一项业余爱好项目时可以做的最简单的事情。
UPDATE: I'm a dork and didn't see the forest for the trees on this one. I don't need a parallel array at all. That's my old 1.1 brain creeping in. Thanks to folks in the comments. It works fine just like this. I'm not sure why I thought it didn't work when I tried it before. Thanks folks!
更新:我是一个傻瓜,没有看到森林上的树木。 我根本不需要并行数组。 那是我的旧1.1大脑在蠕动。感谢其他人的评论。 像这样工作正常。 我不确定为什么我以前尝试过时认为它不起作用。 谢谢大家!
namespace Poo
{
public class Foo
{
public Foo() { FooReadings = new List(); }
[XmlArray("FooReadings")] //Even this attribute isn't really needed if you accept the default.
public List<FooReading> FooReadings;
}
public class FooReading
{
public FooReading() { }
public FooReading(DateTime date, decimal thing2)
{
this.Thing2 = thing2;
this.Date = date;
}
public decimal Thing2;
public DateTime Date;
}
}
The technique below is useful for other things, but not in this instance.
下面的技术可用于其他用途,但在这种情况下无效。
namespace Poo
{
public class Foo
{
public Foo() { FooReadings = new List(); }
[XmlIgnore]
public List<FooReading> FooReadings;
[XmlArray("FooReadings")]
public FooReading[] ArrayFooReadings
{
get { return FooReadings.ToArray(); }
set { FooReadings = new List(value); }
}
}
public class FooReading
{
public FooReading() { }
public FooReading(DateTime date, decimal thing2)
{
this.Thing2 = thing2;
this.Date = date;
}
public decimal Thing2;
public DateTime Date;
}
}
The "Real List<>" is ignored and the "fake" one is presented as an Array in the Getters/Setter. Not pretty, to be sure.
“ Real List <>”将被忽略,而“伪造”列表将在Getters / Setter中显示为数组。
当然不漂亮。
What better ways are there that you prefer?
您更喜欢哪种更好的方法?
翻译自: https://www.hanselman.com/blog/xmlserializing-a-generic-listltgt
xml序列化与反序列化