.NET 可以在没有 If 的情况下将“Yes”和“No”转换为布尔值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2872710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:19:08  来源:igfitidea点击:

Can .NET convert "Yes" & "No" to boolean without If?

.netcastingboolean

提问by hawbsl

You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:

你会认为有一种方法可以使用 DirectCast、TryCast、CType 等,但它们似乎都被它窒息了,例如:

CType("Yes", Boolean)

You get:

你得到:

System.InvalidCastException - Conversion from string "Yes" to type 'Boolean' is not valid.

System.InvalidCastException - 从字符串“Yes”到类型“Boolean”的转换无效。

回答by slugster

If you think about it, "yes" cannot be converted to bool because it is a language and context specific string.

如果您考虑一下,“yes”不能转换为 bool,因为它是特定于语言和上下文的字符串。

"Yes" is not synonymous with true (especially when your wife says it...!). For things like that you need to convert it yourself; "yes" means "true", "mmmm yeeessss" means "half true, half false, maybe", etc.

“是的”不是真实的同义词(尤其是当你的妻子这么说时......!)。对于这样的事情,你需要自己转换它;“是”的意思是“真的”,“mmmm yeeessss”的意思是“一半是真的,一半是假的,也许”等等。

回答by Rubys

Using this way, you can define conversions from any string you like, to the boolean value you need. 1 is true, 0 is false, obviously.
Benefits: Easily modified. You can add new aliases or remove them very easily.
Cons: Will probably take longer than a simple if. (But if you have multiple alises, it will get hairy)

使用这种方式,您可以定义从您喜欢的任何字符串到您需要的布尔值的转换。1是真的,0是假的,很明显。
优点:易于修改。您可以非常轻松地添加或删除新别名。
缺点:可能比简单的 if 花费的时间更长。(但如果你有多个别名,它会变得毛茸茸的)

enum BooleanAliases {
      Yes = 1,
      Aye = 1,
      Cool = 1,
      Naw = 0,
      No = 0
 }
 static bool FromString(string str) {
      return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str));
 }
 // FromString("Yes") = true
 // FromString("No") = false
 // FromString("Cool") = true
enum BooleanAliases {
      Yes = 1,
      Aye = 1,
      Cool = 1,
      Naw = 0,
      No = 0
 }
 static bool FromString(string str) {
      return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str));
 }
 // FromString("Yes") = true
 // FromString("No") = false
 // FromString("Cool") = true

回答by thelost

No, but you could do like:

不,但你可以这样做:

bool yes = "Yes".equals(yourString);

bool yes = "Yes".equals(yourString);

回答by sshow

private static bool GetBool(string condition)
{
    return condition.ToLower() == "yes";
}

GetBool("Yes"); // true
GetBool("No"); // false

Or another approach using extension methods

或使用扩展方法的另一种方法

public static bool ToBoolean(this string str)
{
    return str.ToLower() == "yes";
}

bool answer = "Yes".ToBoolean(); // true
bool answer = "AnythingOtherThanYes".ToBoolean(); // false

回答by Regent

Slightly off topic, but I needed once for one of my classes to display 'Yes/No' instead of 'True/False' in a property grid, so I've implemented YesNoBooleanConverterderived from BooleanConverterand decorating my property with <TypeConverter(GetType(YesNoBooleanConverter))> _...

有点偏离主题,但我需要一次让我的一个类在属性网格中显示“是/否”而不是“真/假”,所以我实现了YesNoBooleanConverter派生自BooleanConverter和装饰我的属性<TypeConverter(GetType(YesNoBooleanConverter))> _......

回答by Mubashar

You Can't. But you should use it as

你不能。但你应该把它用作

bool result = yourstring.ToLower() == "yes";

回答by ScottJamesSDF

C# 6+ version:

C# 6+ 版本:

public static bool StringToBool(string value) => 
    value.Equals("yes",           StringComparison.CurrentCultureIgnoreCase) ||
    value.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase) || 
    value.Equals("1");`

回答by STLDev

I like the answer that @thelost posted, but I'm reading values from an ADO.Net DataTable and the casing of the string in the DataTable can vary.

我喜欢@thelost 发布的答案,但我正在从 ADO.Net DataTable 读取值,并且 DataTable 中字符串的大小写可能会有所不同。

The value I need to get as a boolean is in a DataTable named childAccountsin a column named Trades.

我需要作为布尔值获取的值位于childAccounts名为Trades.

I implemented a solution like this:

我实现了这样的解决方案:

bool tradeFlag = childAccounts["Trade"].ToString().Equals("yes", StringComparison.InvariantCultureIgnoreCase);

回答by dburtsev

    private bool StrToBool(string value)
    {   // could be yes/no, Yes/No, true/false, True/False, 1/0
        bool b = false;
        if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.TrueString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("1"))
        {
            b = true;
        }
        else if (value.Equals("no", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.FalseString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("0"))
        {
            b = false;
        }
        else
        {   // we should't be here 
            b = false;
        }
        return b;
    }

回答by FirebirdUSA

Here is a simple way to get this done.

这是完成此操作的简单方法。

rv.Complete = If(reader("Complete") = "Yes", True, False)