简体   繁体   English

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

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

I get the error "String was not recognized as a valid boolean" I am coding in C# and can't seems to find out what the problem is.我收到错误“字符串未被识别为有效的布尔值”我正在用 C# 编码,但似乎无法找出问题所在。 Any insight would be very much appreciated.任何见解将不胜感激。 This is my code where it's failing:这是我失败的代码:

    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 will only parse a string of "True" or "False" (case-insensitive). bool.Parse只会解析字符串“True”或“False”(不区分大小写)。

The MSDN documentation for bool.TryParse shows a good example of the types of strings that can be parsed. bool.TryParse的 MSDN 文档显示了可以解析的字符串类型的一个很好的示例。

If your input string is some other variation of "truthiness" you would have to write your own parser.如果您的输入字符串是“真实性”的其他变体,您将不得不编写自己的解析器。 Something like:就像是:

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;
    }
}

If this contains "Y" / "N" you have to do something kind of like this code sample:如果它包含“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");
 }
}

Trying to do something like bool.Parse("Y") will definitely throw an exception.尝试做类似bool.Parse("Y")事情肯定会抛出异常。

The weakness of the code sample above is that if the data is bad (ie it contains something other than a "Y" or "N") it won't detect that.上面代码示例的弱点在于,如果数据是错误的(即它包含除“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;
}

I like Steve's approach a lot as well.我也很喜欢史蒂夫的方法。 One possible variant is as follows:一种可能的变体如下:

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