簡體   English   中英

使用字段或屬性作為xmlnode值

[英]Use a field or property as xmlnode value

我正在嘗試做一個角度課程。 當我將此類序列化為xml時,我想執行以下操作:

<Angle Unit="Degree">90</Angle>

or

<Angle Unit="Radian">3.14......</Angle>

當前,當我序列化我的課程時,我得到以下信息:

<Angle Unit="Degree">
  <Degree>90</Degree>
</Angle>

or

<Angle Unit="Radian">
  <Radian>90</Radian>
</Angle>  

我知道[XmlText]可以用於字符串,但是有沒有必要進行自定義xmlwrite和xmlread的雙精度值或其他值的方法?

下面顯示了我的班級代碼的一部分:

[Serializable]
public struct Angle
{
    [XmlAttribute]
    public UnitType Unit;

    public double Radian
    {
        get;
        set;
    }
    public bool ShouldSerializeRadian();

    public double Degree
    {
        get;
        set;
    }
    public bool ShouldSerializeDegree();
}

與Unit和shouldSerialize我選擇要使用的值。

當我將度數設為90時,弧度的值為1.5707 ...

UnitType是具有度和弧度的枚舉。 unit = unittype.degree將在序列化時使用度數,而unit = unittype.radian radain在序列化時將使用。

我用來選擇要使用的表示形式的代碼如下:

public bool ShouldSerializeRadian() 
{ 
   return (Unit == UnitType.Radian); 
}

不知道這是否是最好的解決方案,但是您可以創建一個代理屬性來處理Serilization / Deserialization。

就像是

[Serializable]
public class Angle 
{
    [XmlAttribute]
    public UnitType Unit;

    [XmlTextAttribute]
    public double Value
    {
        get { return Unit == UnitType.Degree ? Degree : Radian; }
        set
        {
            if (Unit == UnitType.Degree)
            {
                Degree = value;
                return;
            }
            Radian = value;
        }
    }

    [XmlIgnore]
    public double Radian { get; set; }

    [XmlIgnore]
    public double Degree { get; set; }
}

結果:

  <Angle Unit="Radian">70.8</Angle> 
  <Angle Unit="Degree">45.2</Angle>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM