2011-04-25 52 views

回答

1

不要直接將數字序列化爲數字。取而代之的是,創建一個格式化並分析數量的虛擬字符串屬性:

[DataContract] 
public class MyClass 
{ 
    // No DataMember attribute here 
    public double MyProperty { get; set; } 

    // Serialize this property instead 
    [DataMember(Name = "MyProperty")] 
    private string MyPropertyXml 
    { 
     get { return MyProperty.ToString("P", CultureInfo.InvariantCulture); } 
     set 
     { 
      if (string.IsNullOrEmpty(value)) 
      { 
       MyProperty = 0; 
      } 
      else 
      { 
       string s = value.TrimEnd('%', ' '); 
       MyProperty = double.Parse(s, CultureInfo.InvariantCulture)/100; 
      } 
     } 
    } 
} 

它產生以下輸出:

<?xml version="1.0" encoding="utf-16"?> 
<MyClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/"> 
    <MyProperty>42.00 %</MyProperty> 
</MyClass>