我有这样的C#类:C#序列化一类具有一个列表数据成员
public class Test
{
public Test() { }
public IList<int> list = new List<int>();
}
然后我有这样的代码:
Test t = new Test();
t.list.Add(1);
t.list.Add(2);
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
StringWriter sw = new StringWriter();
XmlSerializer xml = new XmlSerializer(t.GetType());
xml.Serialize(sw, t);
当我看从sw输出,它的这样的:
<?xml version="1.0" encoding="utf-16"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
值1,2添加到列表成员变量不显示。
- 那么我该如何解决这个问题?我列出了一个属性,但它似乎仍然不起作用。
- 我在这里使用xml序列化,还有其他序列化器吗?
- 我想要表演!这是最好的方法吗?
--------------- UPDATE BELOW -------------------------
所以实际的类我想序列是这样的:
public class RoutingResult
{
public float lengthInMeters { get; set; }
public float durationInSeconds { get; set; }
public string Name { get; set; }
public double travelTime
{
get
{
TimeSpan timeSpan = TimeSpan.FromSeconds(durationInSeconds);
return timeSpan.TotalMinutes;
}
}
public float totalWalkingDistance
{
get
{
float totalWalkingLengthInMeters = 0;
foreach (RoutingLeg leg in Legs)
{
if (leg.type == RoutingLeg.TransportType.Walk)
{
totalWalkingLengthInMeters += leg.lengthInMeters;
}
}
return (float)(totalWalkingLengthInMeters/1000);
}
}
public IList<RoutingLeg> Legs { get; set; } // this is a property! isnit it?
public IList<int> test{get;set;} // test ...
public RoutingResult()
{
Legs = new List<RoutingLeg>();
test = new List<int>(); //test
test.Add(1);
test.Add(2);
Name = new Random().Next().ToString(); // for test
}
}
但通过串行生成的XML是这样的:
<RoutingResult>
<lengthInMeters>9800.118</lengthInMeters>
<durationInSeconds>1440</durationInSeconds>
<Name>630104750</Name>
</RoutingResult>
???
它忽略了这两个列表?
'XmlSerializer'可能与'IList <>'有问题,如果您重新定义为'List <>'而不是? – Nate 2011-03-30 20:11:51