2011-03-30 33 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也提到的那样。