Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用自定义的真值和假值从Xml中分离布尔值?_C#_Boolean_Serialization - Fatal编程技术网

C# 如何使用自定义的真值和假值从Xml中分离布尔值?

C# 如何使用自定义的真值和假值从Xml中分离布尔值?,c#,boolean,serialization,C#,Boolean,Serialization,我试图将Xml文档反序列化为C#类。Xml如下所示: <response> <result>Success</result> </response> 一种解决方案是按如下方式定义枚举并添加扩展方法: enum SuccessBool { False = -1, Failed = -2, Failure = -3, Unseccessful = -4, Tr

我试图将Xml文档反序列化为C#类。Xml如下所示:

<response>
    <result>Success</result>
</response>

一种解决方案是按如下方式定义枚举并添加扩展方法:

enum SuccessBool
{
    False = -1,
    Failed = -2,
    Failure = -3,
    Unseccessful = -4,                      
    True = 1,
    Success = 2,
    Successful = 3
}

static class SuccessBoolExtenson
{
    public static bool ToBool(this SuccessBool success)
    {
        return (int)success > 0;
    }
}

这将有助于定义成功/不成功的多个定义,并且所有定义都是类型安全的。

定义另一个隐藏的属性,该属性为您进行转换:

[XmlRoot(ElementName="response")]
public class Response()
{
  [XmlElement(ElementName="result")]
  private string ResultInternal { get; set; }

  [XmlIgnore()]
  public bool Result{
    get{
      return this.ResultInternal == "Success";
    }
    set{
      this.ResultInternal = value ? "Success" : "Failed";
    }
  }
}

我在您的示例中添加了XmlIgnore属性,因为如果您对这个类进行序列化,这是防止两个结果以Xml结尾所必需的。
[XmlRoot(ElementName="response")]
public class Response()
{
  [XmlElement(ElementName="result")]
  private string ResultInternal { get; set; }

  [XmlIgnore()]
  public bool Result{
    get{
      return this.ResultInternal == "Success";
    }
    set{
      this.ResultInternal = value ? "Success" : "Failed";
    }
  }
}