为了整洁起见,我想知道是否可以将 Y 或 N 转换为 bool 值?像这样的东西;
bool theanswer = Convert.ToBoolean(input);
长版;
bool theanswer = false;
switch (input)
{
case "y": theanswer = true; break;
case "n": theanswer = false; break
}
最佳答案
不,没有为此内置任何内容。
但是,如果您想默认为 false,您可以使用:
bool theAnswer = (input == "y");
(此处的括号只是为了清楚起见。)
考虑到您的问题文本和您获得的代码之间的差异,您可能需要考虑使其不区分大小写。一种方法:
bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
请注意,使用指定的字符串比较可避免创建新字符串,这意味着您无需担心文化问题...除非您希望执行文化敏感的比较,类(class)。另请注意,我已将文字作为方法调用的“目标”,以避免在 input
为 null
时抛出 NullReferenceException
。
关于c# - 将 Y 或 N 转换为 bool C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3716845/