繁体   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