布尔逻辑与相等性
Coddy 面向 JavaScript 开发者的 C# 课程的第 8 课,共 48 课。
JavaScript 条件接受真值和假值,且 && 可以返回一个操作数。C# 条件要求使用 bool,布尔运算符 && 返回 bool。请使用显式比较或集合计数,而不是照搬 JavaScript 的真值判断。
C# 条件要求使用 bool 表达式,不能使用任意数字或集合。&& 和 || 会短路求值;! 会对布尔值取反。对于字符串操作数,String == 会比较文本内容;而普通类引用使用引用相等性,除非类型改变了这种行为。
JavaScript 参考
const active = true;
console.log(20 >= 18 && active);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");
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 JavaScript 开发者的 C#中的所有课
自己练习: C# 在线编译器