【发布时间】:2011-03-31 18:46:54
【问题描述】:
我有这个 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序列化,还有其他的序列化器吗?
- 我想要表现!这是最好的方法吗?
--------------- 下面更新 ----------- --
所以我要序列化的实际类是这样的:
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<>会怎样?
标签: c# serialization xml-serialization