如何使用DataContractSerializer </objects>序列化列表<objects>

时间:2011-09-05 21:46:09

标签: c# serialization datacontract known-types

服务器和客户端之间共享的库包含接口:

[ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(IClient))]
public interface IServer
{

     // Node interface methods
    [OperationContract(Name = "UploadResults", IsOneWay = true)]
    void UploadResults(string result);
}

实现接口的服务器代码:

public void UploadResults(string result)
{
  try
  {
    // Get portfolio from stream
    DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result)))
    {
      MyClass class = (MyClass)serializer.ReadObject(ms);

      .....   
    }
  }
  catch (Exception ex)
  {
  }
}

客户端代码调用服务器:

 // Send myclass object to server
  try
  {
    // Write portfolio to stream
    DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
    using (var stream = new MemoryStream())
    {
      serializer.WriteObject(stream, myclassObj);

      // Send result back to server
      string result = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Position);
      Server.UploadResults(result);
    }
  }
  catch (Exception ex)
  {
  }

MyClass:

  [DataContract]
  [KnownType(typeof(AClass))]
  [KnownType(typeof(List<AClass>))]
  public class MyClass
  {
    [DataMember]
   public List<AClass> History { get; set; }

    [DataMember]
   public int Count { get; set; }
  }

AClass:

[DataContract]

public class AClass
{
  [DataMember]
 public int x;
 [DataMember]
  public int y;
}

0 个答案:

没有答案