将Y或N转换为布尔C# [英] Casting Y or N to bool C#
问题描述
为了简洁起见,我想知道是否可以将Y或N转换为布尔值?像这样;
Just for neatness sake I was wondering, whether it's possible to cast Y or N to a bool? Something like this;
bool theanswer = Convert.ToBoolean(input);
长版本;
bool theanswer = false;
switch (input)
{
case "y": theanswer = true; break;
case "n": theanswer = false; break
}
推荐答案
不,没有构建任何东西
但是,鉴于您要默认为false,您可以使用:
However, given that you want to default to false, you can just use:
bool theAnswer = (input == "y");
(这里的括号只是为了清楚起见。)
(The bracketing there is just for clarity.)
考虑到问题文本和所获得的代码之间的差异,您可能要考虑使其不区分大小写。一种方法是:
You may want to consider making it case-insensitive though, given the difference between the text of your question and the code you've got. One way of doing this:
bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
请注意,使用指定的字符串比较可避免创建新字符串,这意味着您不需要当然,您会担心文化问题...除非您想要进行文化敏感的比较。还要注意,我已将文字作为方法调用的目标,以避免在输入
NullReferenceException >为 null
。
Note that using the specified string comparison avoids creating a new string, and means you don't need to worry about cultural issues... unless you want to perform a culture-sensitive comparison, of course. Also note that I've put the literal as the "target" of the method call to avoid NullReferenceException
being thrown when input
is null
.
这篇关于将Y或N转换为布尔C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!