我在写将由Silverlight应用程序消耗WCF应用程序的过程。我已经做了大部分的设计工作,我现在做的实现,它已经让我想出了这个问题。

下面的东西存在于我的应用程序的示例:

[DataContract]
class Person
{
    [DataMember]
    private Towel mostRecentlyUsedTowel;

    [DataMember]
    private Gym gym; //the gym that this person attends

    ...
}

[DataContract]
class Gym
{
    [DataMember]
    private List<Towel> towels; //all the towels this gym owns

    ...
}

下面就是我在得到:在我的应用程序mostRecentlyUsedTowel将在毛巾列表人的健身房的东西被人指指点点。我的一些要求将序列化一个Person对象。

时DataContractSerializer的足够聪明,它被要求将对象序列完全相同的情况下两次?如果是这样,它是如何应对的呢?

如果它只是去序列化的同一个实例两次,我应该如何处理这个,所以我不会在链路上传送不必要的数据?

有帮助吗?

解决方案

在以下代码:

[TestMethod]
public void CanSerializePerson()
{
    var towel1 = new Towel() { Id = 1 };
    var towel2 = new Towel() { Id = 2 };
    var towel3 = new Towel() { Id = 3 };
    var gym = new Gym();
    gym.towels.Add(towel1);
    gym.towels.Add(towel2);
    gym.towels.Add(towel3);

    var person = new Person()
    {
      recentlyUsedTowel = towel1,
      gym = gym
    };

    var sb = new StringBuilder();
    using (var writer = XmlWriter.Create(sb))
    {
        var ser = new DataContractSerializer(typeof (Person));
        ser.WriteObject(writer, person);
    }

    throw new Exception(sb.ToString());
}

public class Person
{
    public Towel recentlyUsedTowel { get; set; }
    public Gym gym { get; set; }
}

public class Gym
{
    public Gym()
    {
        towels = new List<Towel>();
    }

    public List<Towel> towels { get; set; }
}


public class Towel
{
    public int Id { get; set; }
}

将计算为:

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org">
  <gym>
    <towels>
      <Towel><Id>1</Id></Towel>
      <Towel><Id>2</Id></Towel>
      <Towel><Id>3</Id></Towel>
    </towels>
  </gym>
  <recentlyUsedTowel><Id>1</Id></recentlyUsedTowel>
</Person>

如果添加的IsReference属性到毛巾类的这样的DataContract属性:

[DataContract(IsReference=true)]
public class Towel
{
    // you have to specify a [DataMember] in this because you are 
    // explicitly adding DataContract
    [DataMember]
    public int Id { get; set; }
}

你会得到一个输出这样的:

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org">
  <gym>
    <towels>
      <Towel z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
        <Id>1</Id>
      </Towel>
      <Towel z:Id="i2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
        <Id>2</Id>
      </Towel>
      <Towel z:Id="i3" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
        <Id>3</Id>
      </Towel>
    </towels>
  </gym>
  <recentlyUsedTowel z:Ref="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" />
</Person>

希望这有助于。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top