布尔逻辑与相等性
Coddy 面向 GDScript 开发者的 C# 课程的第 8 课,共 48 课。
GDScript 会在条件中将 0、空字符串、空数组和 null 视为 false,并且同时接受 and/or/not 和 &&/||/!。C# 条件必须是 bool,并且只使用 &&、|| 和 !。不能直接将 GDScript 中的 if items: 检查复制到 C#,必须显式检查 Length 或 Count。GDScript 的 == 会比较数组内容,而 C# 中数组的 == 会比较引用。
C# 条件必须是 bool 表达式,不能是任意数字或集合。&& 和 || 会进行短路求值;! 会对布尔值取反。对于字符串操作数,String == 会比较文本内容;普通类引用则使用引用相等,除非类型改变了这种行为。
GDScript 参考
extends Node
func _ready() -> void:
var active := true
print("true" if 20 >= 18 and active else "false")Main 中的 C# 语句
bool active = true;
Console.WriteLine((20 >= 18 && active) ? "true" : "false");GDScript 参考代码是完整脚本。C# 代码片段是用于教学的重点示例:挑战文件包含完整的可执行包装代码,上面的代码片段展示了相关声明和语句。
参考输出:
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");
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 C#中的所有课
自己练习: C# 在线编译器