c# - 将 Y 或 N 转换为 bool C#

标签 c# c#-4.0

为了整洁起见,我想知道是否可以将 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)。另请注意,我已将文字作为方法调用的“目标”,以避免在 inputnull 时抛出 NullReferenceException

关于c# - 将 Y 或 N 转换为 bool C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3716845/

相关文章:

asp.net - Css 不适用于已发布的网站

c# - 使用 SKYPE4COM 获取个人资料图片

c# - Xamarin UICollectionViewController 每行显示 2 个单元格?

c# - 如何通过zkemkeeper下载指定时间的考勤记录

c# - 应用(服务)自升级?

c# - 如何使用 directshow.net 合并两个视频文件

.net - 逆向工程 .NET C# 这行是什么意思?

c# - .Net 从哪个版本开始支持 httpclient

c# - StreamWriter 不会写入不存在的文件

c# - xaml 中带有 TreeViewItems 的 ListView