Sac*_*nth 76 c# type-conversion
我有一个string可以是"0"或"1",并保证它不会是其他任何东西.
所以问题是:将此转换为最佳,最简单,最优雅的方法是bool什么?
谢谢.
Ken*_*rey 155
确实非常简单:
bool b = str == "1";
Run Code Online (Sandbox Code Playgroud)
Moh*_*and 73
忽略这个问题的特定需求,虽然将字符串转换为bool永远不是一个好主意,但一种方法是在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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
liv*_*ove 37
我知道这不能回答你的问题,只是为了帮助其他人.如果您尝试将"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!
Run Code Online (Sandbox Code Playgroud)
GET*_*Tah 20
bool b = str.Equals("1")? true : false;
Run Code Online (Sandbox Code Playgroud)
甚至更好,如下面的评论中所示:
bool b = str.Equals("1");
Run Code Online (Sandbox Code Playgroud)
我在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));
}
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码将字符串转换为布尔值.
Convert.ToBoolean(Convert.ToInt32(myString));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
196109 次 |
| 最近记录: |