为了整洁,我想知道,是否有可能将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时,被抛出input的null.
bool theanswer = input.ToLower() == "y";
Run Code Online (Sandbox Code Playgroud)
为字符串创建一个扩展方法,它执行与您在第二个算法中指定的类似的操作,从而清理代码:
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)
正如乔恩所建议的那样,没有像这样的内置.John发布的答案为您提供了正确的方法.只需进一步说明,您可以访问:
http://msdn.microsoft.com/en-us/library/86hw82a3.aspx 链接文本