2011-03-30 70 views
1

我有這樣的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添加到列表成員變量不顯示。

  1. 那麼我該如何解決這個問題?我列出了一個屬性,但它似乎仍然不起作用。
  2. 我在這裏使用xml序列化,還有其他序列化器嗎?
  3. 我想要表演!這是最好的方法嗎?

--------------- 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> 

???

它忽略了這兩個列表?

+1

'XmlSerializer'可能與'IList <>'有問題,如果您重新定義爲'List <>'而不是? – Nate 2011-03-30 20:11:51

回答

4

1)list是一個字段,而不是一個屬性,XmlSerializer的將只與性工作,試試這個:

public class Test 
{  
    public Test() { IntList = new List<int>() }  
    public IList<int> IntList { get; set; } 
} 

2)還有其他Serialiation選項,Binary主另一個,儘管JSON也有一個。

3)二進制可能是最高性能的方式,因爲它通常是直接內存轉儲,並且輸出文件將是最小的。

+2

此外,XmlSerializer不能與IList 一起使用,所以我將成員變量更改爲列表。然後它工作。 – 2011-03-31 10:48:07

1

list不是屬性。將其更改爲公開可見的屬性,並將其提取出來。

1

我覺得如果我使用IList,XmlSerializer不起作用,所以我將它改爲List,這使它工作。正如Nate也提到的那樣。

相關問題