ฉันมีstringที่สามารถเป็น "0" หรือ "1" และรับประกันได้ว่าจะไม่เป็นอย่างอื่น
คำถามก็คือวิธีที่ดีที่สุดง่ายที่สุดและสง่างามที่สุดในการแปลงเป็น a boolคืออะไร?
ฉันมีstringที่สามารถเป็น "0" หรือ "1" และรับประกันได้ว่าจะไม่เป็นอย่างอื่น
คำถามก็คือวิธีที่ดีที่สุดง่ายที่สุดและสง่างามที่สุดในการแปลงเป็น a boolคืออะไร?
คำตอบ:
ไม่สนใจความต้องการเฉพาะของคำถามนี้และในขณะที่ไม่ควรส่งสตริงไปที่บูลวิธีหนึ่งก็คือการใช้เมธอด ToBoolean ()ในคลาส Convert:
bool val = Convert.ToBoolean("true");
หรือวิธีการขยายเพื่อทำแผนที่แปลก ๆ ที่คุณกำลังทำอยู่:
public static class StringExtensions
{
public static bool ToBoolean(this string value)
{
switch (value.ToLower())
{
case "true":
return true;
case "t":
return true;
case "1":
return true;
case "0":
return false;
case "false":
return false;
case "f":
return false;
default:
throw new InvalidCastException("You can't cast that value to a bool!");
}
}
}
FormatExceptionเหมือนConvert.ToBoolean
ฉันรู้ว่านี่ไม่ได้ตอบคำถามของคุณ แต่เพียงเพื่อช่วยเหลือคนอื่น หากคุณกำลังพยายามแปลงสตริง "จริง" หรือ "เท็จ" เป็นบูลีน:
ลองใช้ Boolean.Parse
bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!
bool b = str.Equals("1")? true : false;
หรือดีกว่านั้นตามที่แนะนำในความคิดเห็นด้านล่าง:
bool b = str.Equals("1");
x ? true : falseน่าขบขัน
bool b = str.Equals("1") ทำงานได้ดีและใช้งานง่ายมากขึ้นในตอนแรก
strเป็น Null และคุณต้องการให้ Null แก้ไขเป็น False
ฉันทำบางสิ่งที่ขยายได้มากขึ้นเล็กน้อย Piggybacking ตามแนวคิดของ Mohammad Sepahvand:
public static bool ToBoolean(this string s)
{
string[] trueStrings = { "1", "y" , "yes" , "true" };
string[] falseStrings = { "0", "n", "no", "false" };
if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return true;
if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return false;
throw new InvalidCastException("only the following are supported for converting strings to boolean: "
+ string.Join(",", trueStrings)
+ " and "
+ string.Join(",", falseStrings));
}
ฉันใช้โค้ดด้านล่างเพื่อแปลงสตริงเป็นบูลีน
Convert.ToBoolean(Convert.ToInt32(myString));
นี่คือความพยายามของฉันในการแปลงสตริงที่ให้อภัยมากที่สุดเพื่อบูลที่ยังคงมีประโยชน์โดยพื้นฐานแล้วจะเน้นเฉพาะอักขระตัวแรกเท่านั้น
public static class StringHelpers
{
/// <summary>
/// Convert string to boolean, in a forgiving way.
/// </summary>
/// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
/// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
public static bool ToBoolFuzzy(this string stringVal)
{
string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
bool result = (normalizedString.StartsWith("y")
|| normalizedString.StartsWith("t")
|| normalizedString.StartsWith("1"));
return result;
}
}
private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };
public static bool ToBoolean(this string input)
{
return input != null && PositiveList.Any(λ => λ.Equals(input, StringComparison.OrdinalIgnoreCase));
}
ฉันใช้สิ่งนี้:
public static bool ToBoolean(this string input)
{
//Account for a string that does not need to be processed
if (string.IsNullOrEmpty(input))
return false;
return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
}
ฉันชอบวิธีการขยายและนี่คือวิธีที่ฉันใช้ ...
static class StringHelpers
{
public static bool ToBoolean(this String input, out bool output)
{
//Set the default return value
output = false;
//Account for a string that does not need to be processed
if (input == null || input.Length < 1)
return false;
if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
output = true;
else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
output = false;
else
return false;
//Return success
return true;
}
}
จากนั้นจะใช้มันก็ทำอย่าง ...
bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
myValue = b; //myValue is True
หากคุณต้องการทดสอบว่าสตริงเป็นบูลีนที่ถูกต้องโดยไม่มีข้อยกเว้นใด ๆ ให้ลองทำสิ่งนี้:
string stringToBool1 = "true";
string stringToBool2 = "1";
bool value1;
if(bool.TryParse(stringToBool1, out value1))
{
MessageBox.Show(stringToBool1 + " is Boolean");
}
else
{
MessageBox.Show(stringToBool1 + " is not Boolean");
}
เอาต์พุตis Boolean
และเอาต์พุตสำหรับ stringToBool2 คือ 'ไม่ใช่บูลีน'