布尔逻辑与相等性
Coddy 面向 PHP 开发者的 C# 课程的第 8 课,共 48 课。
PHP 条件接受真值和假值,因此 0、"0"、"" 和空数组都会被视为 false,而 echo true 会输出 1。C# 条件要求使用 bool,C# 的 == 不会像 PHP 的宽松 == 那样进行类型转换。请使用显式比较或集合元素数量,而不要照搬 PHP 的真值测试。
C# 条件要求使用 bool 表达式,不能使用任意数字或集合。&& 和 || 会短路求值;! 会对布尔值取反。对于字符串操作数,String == 会比较文本内容;而普通类引用使用引用相等性,除非该类型改变了这种行为。
PHP 参考
$active = true;
var_dump(20 >= 18 && $active);Main 中的 C# 语句
bool active = true;
Console.WriteLine((20 >= 18 && active) ? "true" : "false");这些是用于讲解的重点片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关声明和语句。
参考输出:
bool(true)C# 输出:
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");
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器