Menu
CoddyTech

布尔逻辑与相等性

Coddy 面向 Luau 开发者的 C# 课程的第 8 课,共 48 课。

Luau 只把 nil 和 false 视为假值,因此 0 和空字符串会被视为真值,而且 and/or 返回其中一个操作数,而不是布尔值。C# 条件要求是 bool,因此数字或字符串不能在没有比较的情况下代替它。Luau 的 and、or、not 和 ~= 在 C# 中分别变为 &&、||、! 和 !=。

C# 条件要求是 bool 表达式,不能是任意数字或集合。&& 和 || 会短路求值;! 会对布尔值取反。对于字符串操作数,字符串的 == 会比较文本内容;而普通类引用使用引用相等,除非类型改变了这种行为。

Luau 参考

local active: boolean = true
print(20 >= 18 and active)

Main 中的 C# 语句

bool active = true;
Console.WriteLine((20 >= 18 && active) ? "true" : "false");

这些是聚焦于教学内容的片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。

参考输出:

true

C# 输出:

true
challenge icon

挑战

简单

在不同的行中读取年龄和小写的 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");
}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Luau 开发者的 C#中的所有课

自己练习: C# 在线编译器