布尔逻辑与相等性
Coddy 面向 C 开发者的 C# 课程的第 8 课,共 48 课。
C 会将任何标量视为条件:非零 int 或非空指针为真,而比较运算会产生 int 值 1 或 0。C# 条件必须是 bool,因此 if (count) 无法编译;应写成 count != 0。此外,对两个 C char 指针使用 == 比较的是地址,比较文本需要使用 strcmp;而 C# 对两个字符串使用 == 比较的是它们的内容。
C# 条件必须是 bool 表达式,不能是任意数字或集合。&& 和 || 会进行短路求值;! 会对布尔值取反。对于字符串操作数,String == 会比较文本内容;而普通类引用使用引用相等,除非类型改变了这种行为。
C 参考示例
#include <stdbool.h>
#include <stdio.h>
int main(void) {
bool active = true;
printf("%s\n", (20 >= 18 && active) ? "true" : "false");
return 0;
}
Main 中的 C# 语句
bool active = true;
Console.WriteLine((20 >= 18 && active) ? "true" : "false");这些是用于讲解的精简代码片段。挑战文件包含完整的可执行封装;上面的代码片段展示了相关的声明和语句。
参考输出:
trueC# 输出:
true挑战
简单分别从不同行读取年龄和小写的 true/false 标志。只有当此人处于活跃状态且年满 18 岁时才返回 true。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取描述中的各行,调用 Exercise.Solve,验证输入未被修改,并在末尾输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。
亲手试试
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = input[1] == "true"; string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result ? "true" : "false");
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 C#中的所有课
自己练习: C# 在线编译器