using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace CSharpNullableLab
{
internal class UserProfile
{
public int Id;
public int? Age;
public bool IsActive;
}
internal class Program
{
private static int? GetUserAgeFromDb(List<UserProfile> rows, int userId)
{
foreach (UserProfile row in rows)
{
if (row.Id == userId)
{
return row.Age;
}
}
return null;
}
private static int? GetConfigValue(Dictionary<string, int> cfg, string key)
{
int val;
if (cfg.TryGetValue(key, out val))
{
return val;
}
return null;
}
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: Declaration, syntactic sugar equivalence & default values
int? num1 = null;
int? num2 = 45;
Nullable<int> fullForm = new Nullable<int>(45);
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolVal = new bool?();
bool sameType = typeof(int?) == typeof(Nullable<int>);
string actual1 = string.Format(
CultureInfo.InvariantCulture,
"sameType={0},eq={1},n1={2},n2={3},n3={4},n4={5},boolEmpty={6}",
sameType,
num2.Equals(fullForm),
num1 ?? 0,
num2 ?? 0,
num3 ?? 0.0,
num4 ?? 0.0,
string.Format("{0}", boolVal) == ""
);
cases.Add(CaseJson(
"nullable_declaration_and_equivalence",
"验证 T? 与 Nullable<T> 类型等价、可空值类型默认值及格式化空串输出",
"sameType=True,eq=True,n1=0,n2=45,n3=0,n4=3.14157,boolEmpty=True",
actual1
));
// Case 2: Null-coalescing operator ?? and chaining
double? d1 = null;
double? d2 = 3.14157;
double r1 = d1 ?? 5.34;
double r2 = d2 ?? 5.34;
int? a = null;
int? b = null;
int? c = 42;
int chained = a ?? b ?? c ?? 0;
string actual2 = string.Format(
CultureInfo.InvariantCulture,
"r1={0},r2={1},chained={2}",
r1, r2, chained
);
cases.Add(CaseJson(
"null_coalescing_operator",
"验证 ?? 空合并运算符兜底默认值与多级链式回退求值",
"r1=5.34,r2=3.14157,chained=42",
actual2
));
// Case 3: HasValue, Value exception, GetValueOrDefault
int? emptyNum = null;
int? filledNum = 42;
string valueErr = "none";
try
{
int unused = emptyNum.Value;
valueErr = unused.ToString();
}
catch (InvalidOperationException)
{
valueErr = "InvalidOperationException";
}
string actual3 = string.Format(
"emptyHas={0},filledHas={1},filledVal={2},def0={3},def99={4},coal99={5},err={6}",
emptyNum.HasValue,
filledNum.HasValue,
filledNum.Value,
emptyNum.GetValueOrDefault(),
emptyNum.GetValueOrDefault(99),
emptyNum ?? 99,
valueErr
);
cases.Add(CaseJson(
"nullable_members_and_exception",
"验证 HasValue、GetValueOrDefault 重载以及对 null 可空类型读取 Value 抛出 InvalidOperationException",
"emptyHas=False,filledHas=True,filledVal=42,def0=0,def99=99,coal99=99,err=InvalidOperationException",
actual3
));
// Case 4: Practical scenarios (DB nullable mapping & optional config)
List<UserProfile> users = new List<UserProfile>
{
new UserProfile { Id = 1, Age = 28, IsActive = true },
new UserProfile { Id = 2, Age = null, IsActive = false }
};
int? age1 = GetUserAgeFromDb(users, 1);
int? age2 = GetUserAgeFromDb(users, 2);
string display1 = age1.HasValue ? string.Format("用户年龄:{0}", age1.Value) : "年龄未知";
string display2 = age2.HasValue ? string.Format("用户年龄:{0}", age2.Value) : "年龄未知";
Dictionary<string, int> cfg = new Dictionary<string, int>();
int actualTimeout = GetConfigValue(cfg, "timeout") ?? 30;
cfg["timeout"] = 60;
int customTimeout = GetConfigValue(cfg, "timeout") ?? 30;
string actual4 = string.Format(
"u1={0},u2={1},tDef={2},tCfg={3}",
display1, display2, actualTimeout, customTimeout
);
cases.Add(CaseJson(
"nullable_db_and_config_scenarios",
"验证数据库可空列映射与缺失配置项兜底默认值的工程用法",
"u1=用户年龄:28,u2=年龄未知,tDef=30,tCfg=60",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":{0},\"cases\":[{1}]}}",
Esc("CLR " + Environment.Version.ToString()),
string.Join(",", cases.ToArray())
));
}
}
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
入口文件:projects/csharp-nullable-lab/ExploreNullable.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreNullable.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1344.zip