Tôi có một giá trị stringcó thể là "0" hoặc "1" và được đảm bảo rằng nó sẽ không phải là bất kỳ thứ gì khác.
Vì vậy, câu hỏi là: cách tốt nhất, đơn giản nhất và thanh lịch nhất để chuyển đổi này thành a là boolgì?
Tôi có một giá trị stringcó thể là "0" hoặc "1" và được đảm bảo rằng nó sẽ không phải là bất kỳ thứ gì khác.
Vì vậy, câu hỏi là: cách tốt nhất, đơn giản nhất và thanh lịch nhất để chuyển đổi này thành a là boolgì?
Câu trả lời:
Thực sự khá đơn giản:
bool b = str == "1";
Bỏ qua các nhu cầu cụ thể của câu hỏi này và mặc dù truyền một chuỗi thành bool không bao giờ là một ý tưởng hay, nhưng có một cách là sử dụng phương thức ToBoolean () trên lớp Convert:
bool val = Convert.ToBoolean("true");
hoặc một phương thức mở rộng để thực hiện bất kỳ ánh xạ kỳ lạ nào bạn đang làm:
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!");
}
}
}
FormatExceptionnhư Convert.ToBoolean .
Tôi biết điều này không trả lời câu hỏi của bạn, mà chỉ để giúp những người khác. Nếu bạn đang cố gắng chuyển đổi chuỗi "true" hoặc "false" thành boolean:
Hãy thử 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;
Hoặc thậm chí tốt hơn, như được đề xuất trong một bình luận bên dưới:
bool b = str.Equals("1");
x ? true : falsehài hước.
bool b = str.Equals("1") Hoạt động tốt và trực quan hơn ngay từ cái nhìn đầu tiên.
strlà Null và bạn muốn Null giải quyết là False.
Tôi đã thực hiện một thứ gì đó có thể mở rộng hơn một chút, Cõng theo khái niệm của 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));
}
Tôi đã sử dụng mã bên dưới để chuyển đổi một chuỗi thành boolean.
Convert.ToBoolean(Convert.ToInt32(myString));
Đây là nỗ lực của tôi về chuỗi dễ tha thứ nhất thành chuyển đổi bool vẫn hữu ích, về cơ bản chỉ khóa ký tự đầu tiên.
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));
}
Tôi sử dụng cái này:
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");
}
Tôi thích các phương pháp mở rộng và đây là phương pháp tôi sử dụng ...
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;
}
}
Sau đó, để sử dụng nó, chỉ cần làm một cái gì đó như ...
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
Nếu bạn muốn kiểm tra xem một chuỗi có phải là Boolean hợp lệ mà không có bất kỳ ngoại lệ nào được đưa ra hay không, bạn có thể thử cách này:
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");
}
đầu ra is Boolean
và đầu ra cho stringToBool2 là: 'không phải là Boolean'