gpt4 book ai didi

wcf - DataContractSerializer 每个请求多次序列化同一个对象

转载 作者:行者123 更新时间:2023-12-04 14:14:20 24 4
gpt4 key购买 nike

我正在编写一个将由 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 属性添加到 Towel 类的 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>

希望这可以帮助。

关于wcf - DataContractSerializer 每个请求多次序列化同一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/790861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com