将Y或N转换为bool C#

won*_*nea 18 c# c#-4.0

为了整洁,我想知道,是否有可能将Y或N投入布尔?像这样的东西;

bool theanswer = Convert.ToBoolean(input);
Run Code Online (Sandbox Code Playgroud)

长版;

bool theanswer = false;
switch (input)
{
   case "y": theanswer = true; break;
   case "n": theanswer = false; break
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 42

不,没有内置任何东西.

但是,如果您希望默认为false,则可以使用:

bool theAnswer = (input == "y");
Run Code Online (Sandbox Code Playgroud)

(包围就是为了清晰起见.)

考虑到问题文本与您获得的代码之间的差异,您可能需要考虑使其不区分大小写.一种方法:

bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
Run Code Online (Sandbox Code Playgroud)

请注意,使用指定的字符串比较可以避免创建新字符串,这意味着您不必担心文化问题......当然,除非您想要执行文化敏感的比较.另外请注意,我已经把文字作为方法调用,以避免"目标" NullReferenceException时,被抛出inputnull.

  • 在第二个例子中,很好地防止输入为空.要记住这一点. (9认同)
  • (输入??"").Equals("y",StringComparison.OrdinalIgnoreCase); 使意图清楚,我们检查变量的值等于某些常数,反之亦然.与if(NULL == ptr)相同的c ++争论 (2认同)

Joe*_*ton 8

bool theanswer = input.ToLower() == "y";
Run Code Online (Sandbox Code Playgroud)

  • @Gertjan - 请提供一个链接以供考虑最佳实践,而不是一概而论。根据应用程序的需要,我认为 NullReferenceException 会在执行这样的片段的级别上出现。 (2认同)

Ric*_*III 5

为字符串创建一个扩展方法,它执行与您在第二个算法中指定的类似的操作,从而清理代码:

public static bool ToBool(this string input)
{
    // input will never be null, as you cannot call a method on a null object
    if (input.Equals("y", StringComparison.OrdinalIgnoreCase))
    {
         return true;
    }
    else if (input.Equals("n", StringComparison.OrdinalIgnoreCase))
    {
         return false;
    }
    else
    {
         throw new Exception("The data is not in the correct format.");
    }
}
Run Code Online (Sandbox Code Playgroud)

并调用代码:

if (aString.ToBool())
{
     // do something
}
Run Code Online (Sandbox Code Playgroud)


sum*_*mer 5

正如乔恩所建议的那样,没有像这样的内置.John发布的答案为您提供了正确的方法.只需进一步说明,您可以访问:

http://msdn.microsoft.com/en-us/library/86hw82a3.aspx 链接文本