私はstring「0」または「1」のいずれかであることができるを持っています、そしてそれが他のものにならないことが保証されています。
したがって、問題は、これをに変換するための最良の、最も単純で、最もエレガントな方法はbool何ですか?
私はstring「0」または「1」のいずれかであることができるを持っています、そしてそれが他のものにならないことが保証されています。
したがって、問題は、これをに変換するための最良の、最も単純で、最もエレガントな方法はbool何ですか?
回答:
この質問の特定のニーズを無視し、文字列をブール値にキャストすることは決して良い考えではありませんが、1つの方法はConvertクラスでToBoolean()メソッドを使用することです。
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!");
}
}
}
私はこれがあなたの質問に答えないことを知っていますが、他の人々を助けるためだけです。「true」または「false」の文字列をブール値に変換しようとしている場合:
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として解決したい場合は、それほど直感的ではありません。
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;
}
}
私は拡張メソッドが大好きで、これは私が使用するものです...
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の出力は次のとおりです: 'ブール値ではありません'