C# 判断
系统梳理 C# 判断控制结构(if、if...else、嵌套 if、switch、嵌套 switch)、C# 6.0 Null 条件运算符 ?. 概念及三元条件运算符 ? : 的求值规则与实测。
学完这一章,你能够
- 系统梳理 C# 判断控制结构(if、if...else、嵌套 if、switch、嵌套 switch)、C# 6.0 Null 条件运算符 ?. 概念及三元条件运算符 ? : 的求值规则与实测。
判断控制结构与分支语句家族
判断结构用于根据一个或多个布尔条件的真假决定程序的执行路径:条件为真时执行必需分支,条件为假时可执行可选替代分支。C# 提供了完整的分支工具集,涵盖 `if`、`if...else`、嵌套 `if`、`switch`、嵌套 `switch` 以及自 C# 6.0 引入用于安全成员访问的 Null 条件运算符 `?.`(详见下方判断语句参考表)。本站 `ExploreDecision.cs` 已对成绩分级 `if/else if/else` 嵌套分支以及双层 `switch` 路由分派进行了本地实测。
三元条件运算符 ? : 与单分支求值
条件运算符 `? :`(一般形式为 `Exp1 ? Exp2 : Exp3;`)可以简洁替代返回单值的 `if...else` 结构。求值时首先计算布尔条件 `Exp1`:若为 `true` 则仅计算 `Exp2` 并作为整个表达式的值;若为 `false` 则仅计算 `Exp3` 作为结果,未命中的分支不会被求值(注意问号与冒号的位置搭配)。此外针对 C# 6.0+ 的 `?.` 空条件访问,本机 C# 5.0 实验室以等价的显式判空保护 `(obj != null) ? obj.Name : null` 验证了非空取值与空引用安全返回 `null` 的一致语义。
C# 判断语句与空条件运算符参考表
| 语句 / 运算符 | 功能说明 |
| `if` 语句 | 由一个布尔表达式后跟一条语句或语句块组成,条件为真时执行。 |
| `if...else` 语句 | 在 `if` 后附加可选 `else` 分支,布尔条件为假时执行 `else` 块。 |
| 嵌套 `if` 语句 | 在 `if` 或 `else if` 分支内部继续嵌套 `if` / `else if` 处理多维条件。 |
| `switch` 语句 | 根据单个表达式匹配多个常量 `case` 分支(C# 禁止非空 case 隐式穿透,须以 `break`/`return` 结束)。 |
| 嵌套 `switch` 语句 | 在外层 `switch` 的某个 `case` 分支内再嵌套一层 `switch` 进行二级分派。 |
| Null 条件运算符 `?.`(C# 6.0+) | 在左侧对象非空时访问其属性或方法,为 `null` 时短路返回 `null`,避免冗长的层层判空 `if`。 |
实测 if/else 嵌套分级、双层 switch 路由、三元 ?: 单分支求值与等价空值保护
展开查看收起
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
public class ExploreDecision
{
private class UserProfile
{
public string Name;
}
private static string JsonEscape(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder();
sb.Append('"');
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20)
sb.Append(string.Format(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)c));
else
sb.Append(c);
break;
}
}
sb.Append('"');
return sb.ToString();
}
private static string MakeCase(string name, string summary, string expectedJson, string actualJson)
{
bool passed = string.Equals(expectedJson, actualJson, StringComparison.Ordinal);
return string.Format(
CultureInfo.InvariantCulture,
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
JsonEscape(name),
JsonEscape(summary),
expectedJson,
actualJson,
passed ? "true" : "false"
);
}
private static string ClassifyScore(int score, bool bonus)
{
if (score >= 90)
{
if (bonus)
{
return "A+";
}
else
{
return "A";
}
}
else if (score >= 60)
{
return "Pass";
}
else
{
return "Fail";
}
}
private static string RouteAction(int category, char code)
{
switch (category)
{
case 1:
switch (code)
{
case 'R': return "cat1-read";
case 'W': return "cat1-write";
default: return "cat1-other";
}
case 2:
return "cat2-default";
default:
return "unknown";
}
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
List<string> cases = new List<string>();
// Case 1: if, if...else, else if, nested if
string actualIf = string.Format(
CultureInfo.InvariantCulture,
"{{\"s95_bonus\":{0},\"s92_plain\":{1},\"s75\":{2},\"s40\":{3}}}",
JsonEscape(ClassifyScore(95, true)),
JsonEscape(ClassifyScore(92, false)),
JsonEscape(ClassifyScore(75, false)),
JsonEscape(ClassifyScore(40, false))
);
string expectedIf = "{\"s95_bonus\":\"A+\",\"s92_plain\":\"A\",\"s75\":\"Pass\",\"s40\":\"Fail\"}";
cases.Add(MakeCase(
"if_else_and_nested_if",
"实测 if、if...else、else if 阶梯与嵌套 if 条件分支分流",
expectedIf,
actualIf
));
// Case 2: switch and nested switch
string actualSwitch = string.Format(
CultureInfo.InvariantCulture,
"{{\"c1_R\":{0},\"c1_X\":{1},\"c2\":{2},\"c9\":{3}}}",
JsonEscape(RouteAction(1, 'R')),
JsonEscape(RouteAction(1, 'X')),
JsonEscape(RouteAction(2, 'R')),
JsonEscape(RouteAction(9, 'R'))
);
string expectedSwitch = "{\"c1_R\":\"cat1-read\",\"c1_X\":\"cat1-other\",\"c2\":\"cat2-default\",\"c9\":\"unknown\"}";
cases.Add(MakeCase(
"switch_and_nested_switch",
"实测 switch 多值分支、default 兜底及嵌套 switch 分派",
expectedSwitch,
actualSwitch
));
// Case 3: Ternary ? : operator and single-branch evaluation
int branchCalls = 0;
Func<string> trueBranch = delegate() { branchCalls += 1; return "yes"; };
Func<string> falseBranch = delegate() { branchCalls += 10; return "no"; };
string t1 = (10 > 3) ? trueBranch() : falseBranch();
string t2 = (10 < 3) ? trueBranch() : falseBranch();
string actualTernary = string.Format(
CultureInfo.InvariantCulture,
"{{\"t1\":{0},\"t2\":{1},\"branch_calls_mask\":{2}}}",
JsonEscape(t1),
JsonEscape(t2),
branchCalls
);
string expectedTernary = "{\"t1\":\"yes\",\"t2\":\"no\",\"branch_calls_mask\":11}";
cases.Add(MakeCase(
"ternary_conditional_operator",
"实测 Exp1 ? Exp2 : Exp3 真假分支返回值且仅对命中分支求值",
expectedTernary,
actualTernary
));
// Case 4: C# 5 null-guard equivalent to C# 6 null-conditional (?.)
UserProfile existing = new UserProfile();
existing.Name = "Alice";
UserProfile missing = null;
string name1 = (existing != null) ? existing.Name : null;
string name2 = (missing != null) ? missing.Name : null;
string actualNull = string.Format(
CultureInfo.InvariantCulture,
"{{\"existing\":{0},\"missing_is_null\":{1}}}",
JsonEscape(name1),
(name2 == null) ? "true" : "false"
);
string expectedNull = "{\"existing\":\"Alice\",\"missing_is_null\":true}";
cases.Add(MakeCase(
"null_guard_equivalent_for_null_conditional",
"以 C# 5 显式空值保护实测与 C# 6.0 ?. 运算符等价的安全成员访问语义",
expectedNull,
actualNull
));
string version = ".NET Framework " + Environment.Version.ToString() + " (csc.exe C# 5.0)";
Console.WriteLine(string.Format(
CultureInfo.InvariantCulture,
"{{\"version\":{0},\"cases\":[{1}]}}",
JsonEscape(version),
string.Join(",", cases.ToArray())
));
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不会。条件运算符 `? :` 严格采用惰性单分支求值:仅当 `cond` 为 `true` 时求值 `FuncA()`,为 `false` 时才求值 `FuncB()`,未选中的分支完全不执行。