我有這樣的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