我得到错误“字符串未被识别为有效的布尔值”我在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;
}
答案 0 :(得分:4)
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;
}
}
答案 1 :(得分:1)
如果包含&#34; Y&#34; /&#34; N&#34;你必须做一些类似这样的代码示例:
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")
之类的操作肯定会引发异常。
上面的代码示例的弱点是,如果数据不好(即它包含的不是&#34; Y&#34;或&#34; N&#34;),它将无法检测到这一点。
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");
}
}