2009-04-26 56 views
4

我正在編寫將由Silverlight應用程序使用的WCF應用程序。我已經完成了大部分設計工作,現在正在執行,這讓我想到了這個問題。DataContractSerializer每次請求多次對同一對象進行序列化

這裏的東西存在於我的應用程序的示例:

[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是否足夠智能以注意到它被要求兩次序列化完全相同的對象實例?如果是這樣,它是如何處理它的?

如果它只是將序列化相同的實例兩次,我應該如何處理這個,所以我不通過鏈接發送不必要的數據?

回答

7

下面的代碼:如果您添加的IsReference屬性的毛巾類的這樣的DataContract屬性

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

[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; } 
} 

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

希望這有助於。

+0

這正是我一直在尋找的。非常感謝你。 – Craig 2009-04-26 14:35:36

相關問題