繁体   English   中英

字符串未被识别为有效的布尔值 C#

[英]String was not recognized as a valid boolean C#

我收到错误“字符串未被识别为有效的布尔值”我正在用 C# 编码,但似乎无法找出问题所在。 任何见解将不胜感激。 这是我失败的代码:

    public static SalesInfo Parse(string stringValue)
    {
        string[] words;
        SalesInfo salesInfo = new SalesInfo();

        words = StringMethods.ParseCsvString(stringValue.Trim());
        salesInfo.ID = int.Parse(words[0]);
        salesInfo.Name = words[1];
        salesInfo.City = words[2];
        salesInfo.Senior = bool.Parse(words[3]);<----Error here
        salesInfo.Veteran = bool.Parse(words[4]);
        salesInfo.PurDate = Date.Parse(words[5]);
        salesInfo.ItemPrice = Double.Parse(words[6]);
        salesInfo.Quantity = int.Parse(words[7]);

        return salesInfo;
    }

bool.Parse只会解析字符串“True”或“False”(不区分大小写)。

bool.TryParse的 MSDN 文档显示了可以解析的字符串类型的一个很好的示例。

如果您的输入字符串是“真实性”的其他变体,您将不得不编写自己的解析器。 就像是:

public static SalesInfo Parse(string stringValue)
{
    ...cut for brevity...

    salesInfo.Senior = ParseBool(words[3]);

    return salesInfo;
}

public bool ParseBool(string input)
{
    switch (input.ToLower())
    {
        case "y":
        case "yes":
            return true;
        default:
            return false;
    }
}

如果它包含“Y”/“N”,您必须执行类似于此代码示例的操作:

void Method()
{
 string arr = new[] { "Y", "n", "N", "y"};

 foreach (string value in arr)
 {
    // If it DOES equal "y", then this is "true"; otherwise "false"
    bool boolean = value.Trim().ToLower().Equals("y");
 }
}

尝试做类似bool.Parse("Y")事情肯定会抛出异常。

上面代码示例的弱点在于,如果数据是错误的(即它包含除“Y”或“N”以外的其他内容),则它不会检测到。

public static SalesInfo Parse(string stringValue)
{
    string[] words;
    SalesInfo salesInfo = new SalesInfo();

    words = StringMethods.ParseCsvString(stringValue.Trim());
    salesInfo.ID = int.Parse(words[0]);
    salesInfo.Name = words[1];
    salesInfo.City = words[2];
    // Solution here
    salesInfo.Senior = words[3].Trim().ToLower().Equals("y");
    salesInfo.Veteran = bool.Parse(words[4]);
    salesInfo.PurDate = Date.Parse(words[5]);
    salesInfo.ItemPrice = Double.Parse(words[6]);
    salesInfo.Quantity = int.Parse(words[7]);

    return salesInfo;
}

我也很喜欢史蒂夫的方法。 一种可能的变体如下:

public bool ParseBool(string input)
{
   if (input == null)
      throw new ArgumentNullException("input");

   switch (input.ToLower())
   {
       case "y":
       case "yes":
           return true;

       case "n":
       case "no":
            return false;

       // If the CSV file is wrong (i.e. it contains "bad" data)
       default:
           return throw new ArgumentException("bad data - not a bool");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM