csharp
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace CSharpKeywordsCompleteDemo
{
#region 1. 类型关键字演示
/// <summary>
/// 演示所有值类型和引用类型
/// </summary>
class TypeKeywordsDemo
{
public void DemonstrateTypes()
{
Console.WriteLine("========== 1. 类型关键字 ==========");
// 值类型(存储在栈上)
bool boolean = true; // 布尔类型
byte byteValue = 255; // 无符号字节 0-255
sbyte sbyteValue = -128; // 有符号字节 -128-127
char charValue = 'A'; // Unicode字符
short shortValue = 32767; // 16位整数
ushort ushortValue = 65535; // 16位无符号整数
int intValue = 2147483647; // 32位整数
uint uintValue = 4294967295U; // 32位无符号整数
long longValue = 9223372036854775807L; // 64位整数
ulong ulongValue = 18446744073709551615UL; // 64位无符号整数
float floatValue = 3.14159f; // 单精度浮点数
double doubleValue = 3.14159265358979; // 双精度浮点数
decimal decimalValue = 99.99m; // 高精度小数(财务用)
// 引用类型(存储在堆上)
object objectValue = "万物皆对象"; // 所有类型的基类
string stringValue = "Hello C#"; // 字符串(不可变)
// 自定义引用类型
Person person = new Person { Name = "张三", Age = 25 };
Console.WriteLine($"bool: {boolean}");
Console.WriteLine($"int: {intValue}");
Console.WriteLine($"double: {doubleValue}");
Console.WriteLine($"decimal: {decimalValue} (财务计算推荐)");
Console.WriteLine($"string: {stringValue}");
Console.WriteLine($"object: {objectValue}");
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
#endregion
#region 2. 访问修饰符演示
/// <summary>
/// 演示所有访问修饰符的可见性
/// </summary>
public class AccessModifiersDemo
{
public string PublicField = "🔓 任何地方都可访问";
private string PrivateField = "🔒 仅本类可访问";
protected string ProtectedField = "🛡️ 本类及派生类可访问";
internal string InternalField = "📦 同一程序集可访问";
protected internal string ProtectedInternalField = "📦🛡️ 同一程序集或派生类";
private protected string PrivateProtectedField = "📦🔒 同一程序集的派生类";
public void ShowAccessibleFields()
{
Console.WriteLine("\n========== 2. 访问修饰符 ==========");
Console.WriteLine($"✅ 本类中可以访问: {PrivateField}");
Console.WriteLine($"✅ 本类中可以访问: {ProtectedField}");
Console.WriteLine($"✅ 本类中可以访问: {InternalField}");
}
}
// 派生类演示 protected 和 protected internal
class DerivedClass : AccessModifiersDemo
{
public void ShowDerivedAccess()
{
Console.WriteLine($"✅ 派生类可访问: {ProtectedField}");
Console.WriteLine($"✅ 派生类可访问: {ProtectedInternalField}");
Console.WriteLine($"❌ 派生类不可访问: PrivateField (编译错误)");
}
}
#endregion
#region 3. 类成员修饰符演示
/// <summary>
/// 演示 abstract, virtual, override, sealed, static, const, readonly
/// </summary>
abstract class Animal // abstract: 不能实例化
{
public string Name { get; set; }
// abstract: 派生类必须实现
public abstract void MakeSound();
// virtual: 派生类可以重写
public virtual void Eat()
{
Console.WriteLine("动物在吃东西...");
}
}
class Dog : Animal
{
// override: 重写抽象方法(必须)
public override void MakeSound()
{
Console.WriteLine("🐕 汪汪汪!");
}
// override: 重写虚方法(可选)
public override void Eat()
{
base.Eat(); // base: 调用基类方法
Console.WriteLine("🐕 狗狗在吃骨头...");
}
// new: 隐藏基类成员
public new string Name
{
get => base.Name;
set => base.Name = $"狗狗: {value}";
}
}
sealed class Cat : Animal // sealed: 不能被继承
{
public override void MakeSound()
{
Console.WriteLine("🐱 喵喵喵!");
}
public override void Eat()
{
Console.WriteLine("🐱 猫咪在吃鱼...");
}
}
class StaticConstReadonlyDemo
{
// const: 编译时常量,必须在声明时赋值
public const double PI = 3.14159;
// readonly: 运行时常量,可在构造函数赋值
public readonly int ReadOnlyValue;
// static: 属于类型本身
public static int StaticCounter = 0;
// static readonly: 静态只读
public static readonly DateTime StartupTime;
static StaticConstReadonlyDemo()
{
StartupTime = DateTime.Now; // 静态构造函数中赋值
}
public StaticConstReadonlyDemo(int value)
{
ReadOnlyValue = value; // 只能在构造函数中赋值
}
public void Demonstrate()
{
Console.WriteLine("\n========== 3. 类成员修饰符 ==========");
Console.WriteLine($"const PI: {PI} (编译时常量)");
Console.WriteLine($"readonly: {ReadOnlyValue} (运行时常量)");
Console.WriteLine($"static counter: {++StaticCounter} (所有实例共享)");
Console.WriteLine($"static readonly: {StartupTime} (静态只读)");
}
}
#endregion
#region 4. 控制流语句演示
/// <summary>
/// 演示所有控制流关键字
/// </summary>
class ControlFlowDemo
{
public void DemonstrateAll()
{
Console.WriteLine("\n========== 4. 控制流语句 ==========");
// if-else 条件分支
int score = 85;
if (score >= 90)
{
Console.WriteLine("if-else: 优秀");
}
else if (score >= 60)
{
Console.WriteLine("if-else: 及格");
}
else
{
Console.WriteLine("if-else: 不及格");
}
// switch-case (支持模式匹配)
string day = "Monday";
string result = day switch
{
"Monday" => "周一",
"Friday" => "周五",
"Saturday" or "Sunday" => "周末",
_ => "工作日"
};
Console.WriteLine($"switch表达式: {result}");
// 传统switch
switch (score / 10)
{
case 10:
case 9:
Console.WriteLine("switch-case: A");
break;
case 8:
Console.WriteLine("switch-case: B");
break;
case 7:
case 6:
Console.WriteLine("switch-case: C");
break;
default:
Console.WriteLine("switch-case: D");
break;
}
// for 循环
Console.Write("for循环: ");
for (int i = 0; i < 5; i++)
{
Console.Write($"{i} ");
}
Console.WriteLine();
// foreach 循环
var fruits = new[] { "苹果", "香蕉", "橙子" };
Console.Write("foreach循环: ");
foreach (var fruit in fruits)
{
Console.Write($"{fruit} ");
}
Console.WriteLine();
// while 循环
int counter = 0;
Console.Write("while循环: ");
while (counter < 3)
{
Console.Write($"{counter} ");
counter++;
}
Console.WriteLine();
// do-while 循环(至少执行一次)
counter = 0;
Console.Write("do-while循环: ");
do
{
Console.Write($"{counter} ");
counter++;
} while (counter < 3);
Console.WriteLine();
// break 和 continue
Console.Write("break和continue: ");
for (int i = 0; i < 5; i++)
{
if (i == 2) continue; // 跳过2
if (i == 4) break; // 到达4时停止
Console.Write($"{i} ");
}
Console.WriteLine("(跳过了2,在4停止)");
// return 退出方法
Console.WriteLine("return演示: 下面会提前返回");
ReturnDemo();
}
private void ReturnDemo()
{
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
Console.WriteLine($"遇到{i},return退出方法");
return; // 退出整个方法
}
Console.WriteLine($" 处理{i}");
}
Console.WriteLine("这行不会执行");
}
}
#endregion
#region 5. 异常处理演示
/// <summary>
/// 演示 try, catch, finally, throw
/// </summary>
class ExceptionHandlingDemo
{
public void DemonstrateExceptions()
{
Console.WriteLine("\n========== 5. 异常处理 ==========");
try
{
Console.WriteLine("try: 执行可能出错的代码");
int result = Divide(10, 0);
Console.WriteLine($"结果: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"catch: 捕获特定异常 - {ex.Message}");
throw; // throw: 重新抛出(保留堆栈)
}
catch (Exception ex) when (ex.Message.Contains("特定条件"))
{
// when: 异常筛选器
Console.WriteLine($"catch when: 条件满足时捕获 - {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"catch: 捕获所有异常 - {ex.Message}");
}
finally
{
Console.WriteLine("finally: 无论是否异常都会执行(清理资源)");
}
// checked/unchecked 演示
try
{
int max = int.MaxValue;
// checked: 检查溢出
int overflow = checked(max + 1);
}
catch (OverflowException ex)
{
Console.WriteLine($"checked: 检测到溢出 - {ex.Message}");
}
// unchecked: 忽略溢出
int noCheck = unchecked(int.MaxValue + 1);
Console.WriteLine($"unchecked: 忽略溢出,结果为 {noCheck}");
}
private int Divide(int a, int b)
{
if (b == 0)
{
throw new ArgumentException("除数不能为零", nameof(b)); // 主动抛出异常
}
return a / b;
}
}
#endregion
#region 6. LINQ 演示
/// <summary>
/// 演示所有 LINQ 关键字
/// </summary>
class LinqKeywordsDemo
{
public void DemonstrateLinq()
{
Console.WriteLine("\n========== 6. LINQ 关键字 ==========");
var students = new[]
{
new { Name = "张三", Grade = 85, Class = "一班", Score = 450 },
new { Name = "李四", Grade = 92, Class = "一班", Score = 480 },
new { Name = "王五", Grade = 78, Class = "二班", Score = 420 },
new { Name = "赵六", Grade = 88, Class = "二班", Score = 460 },
new { Name = "钱七", Grade = 95, Class = "一班", Score = 490 }
};
// 完整 LINQ 查询语法
var query = from student in students // from: 数据源
where student.Grade >= 80 // where: 筛选
let isExcellent = student.Grade >= 90 // let: 引入临时变量
orderby student.Grade descending // orderby: 排序
group student by student.Class into classGroup // group...into: 分组
select new // select: 投影
{
ClassName = classGroup.Key,
Count = classGroup.Count(),
AverageGrade = classGroup.Average(s => s.Grade),
Students = classGroup
};
foreach (var classInfo in query)
{
Console.WriteLine($"📚 {classInfo.ClassName}:");
Console.WriteLine($" 人数: {classInfo.Count}, 平均分: {classInfo.AverageGrade:F1}");
Console.WriteLine(" 学生:");
foreach (var student in classInfo.Students)
{
Console.WriteLine($" - {student.Name}: {student.Grade}分");
}
}
// 连接查询 (join)
var classes = new[]
{
new { ClassId = "一班", Teacher = "王老师" },
new { ClassId = "二班", Teacher = "李老师" }
};
var joinQuery = from student in students
join cls in classes on student.Class equals cls.ClassId
select new
{
student.Name,
student.Grade,
cls.Teacher
};
Console.WriteLine("\n班级和教师信息:");
foreach (var item in joinQuery)
{
Console.WriteLine($" {item.Name}: {item.Grade}分, 班主任: {item.Teacher}");
}
}
}
#endregion
#region 7. 异步编程演示
/// <summary>
/// 演示 async, await
/// </summary>
class AsyncProgrammingDemo
{
public async Task DemonstrateAsync()
{
Console.WriteLine("\n========== 7. 异步编程 ==========");
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 开始异步操作 (主线程: {Environment.CurrentManagedThreadId})");
// 异步下载多个文件
var tasks = new List<Task<string>>
{
DownloadDataAsync("文件1", 2000),
DownloadDataAsync("文件2", 1500),
DownloadDataAsync("文件3", 2500)
};
Console.WriteLine("等待所有下载完成...");
string[] results = await Task.WhenAll(tasks);
foreach (var result in results)
{
Console.WriteLine($"✅ {result}");
}
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 所有操作完成");
}
private async Task<string> DownloadDataAsync(string fileName, int delayMs)
{
Console.WriteLine($" ⏳ 开始下载 {fileName} (线程: {Environment.CurrentManagedThreadId})");
await Task.Delay(delayMs); // await: 等待但不阻塞线程
Console.WriteLine($" ✅ 完成下载 {fileName}");
return $"{fileName} 下载完成,耗时 {delayMs}ms";
}
// lock 关键字演示(线程同步)
private readonly object _lockObj = new object();
private int _counter = 0;
public void IncrementCounter()
{
lock (_lockObj) // 确保线程安全
{
_counter++;
Console.WriteLine($"计数器: {_counter} (线程: {Environment.CurrentManagedThreadId})");
}
}
// volatile 关键字:告诉编译器该字段可能被多线程修改
private volatile bool _isRunning = true;
public void StopRunning()
{
_isRunning = false;
}
}
#endregion
#region 8. 属性访问器演示
/// <summary>
/// 演示 get, set, init, value
/// </summary>
class PropertyAccessorsDemo
{
private string _name;
// 传统属性:get 和 set
public string Name
{
get { return _name; }
set { _name = value; } // value: 隐式参数
}
// 表达式体属性 (C# 7.0+)
public string NameShort
{
get => _name;
set => _name = value;
}
// 自动实现属性
public int Age { get; set; }
// 只读属性(只有get)
public DateTime CreatedTime { get; } = DateTime.Now;
// init 访问器 (C# 9.0+): 只能在初始化时设置
public string Email { get; init; }
// 只读字段
private readonly string _id;
public PropertyAccessorsDemo(string email, string id)
{
Email = email; // ✅ init 可以在构造函数中赋值
_id = id; // readonly 字段只能在构造函数中赋值
}
public void Demonstrate()
{
Console.WriteLine("\n========== 8. 属性访问器 ==========");
Console.WriteLine($"Name: {Name}");
Console.WriteLine($"Age: {Age}");
Console.WriteLine($"CreatedTime: {CreatedTime}");
Console.WriteLine($"Email: {Email} (init-only)");
// 以下代码会编译错误:
// Email = "new@email.com"; // ❌ init 属性不能在初始化后修改
}
}
#endregion
#region 9. 泛型约束演示
/// <summary>
/// 演示 where 泛型约束
/// </summary>
class GenericConstraintsDemo
{
// 多种泛型约束组合
public class Repository<T> where T : class, new() // T必须是引用类型且有无参构造函数
{
public T CreateNew()
{
return new T(); // 因为有new()约束,可以创建实例
}
}
public class NumberProcessor<T> where T : struct // T必须是值类型
{
public T Add(T a, T b)
{
// 值类型约束确保安全操作
dynamic da = a;
dynamic db = b;
return da + db;
}
}
public class Sorter<T> where T : IComparable<T> // 实现IComparable接口
{
public T Max(T a, T b)
{
return a.CompareTo(b) > 0 ? a : b;
}
}
public class Container<T, U>
where T : class
where U : struct, IComparable
{
public void Demonstrate()
{
Console.WriteLine($"\n========== 9. 泛型约束 ==========");
Console.WriteLine($"T: {typeof(T).Name} (引用类型)");
Console.WriteLine($"U: {typeof(U).Name} (值类型 + IComparable)");
}
}
public void Demonstrate()
{
var repo = new Repository<Person>();
var person = repo.CreateNew();
Console.WriteLine($"Repository<T> where T : class, new() - 创建了 {person.GetType().Name}");
var processor = new NumberProcessor<int>();
Console.WriteLine($"NumberProcessor<T> where T : struct - 加法: 10 + 20 = {processor.Add(10, 20)}");
var sorter = new Sorter<int>();
Console.WriteLine($"Sorter<T> where T : IComparable - 最大值: Max(5, 10) = {sorter.Max(5, 10)}");
var container = new Container<string, int>();
container.Demonstrate();
}
class Person { }
}
#endregion
#region 10. 不安全代码演示
/// <summary>
/// 演示 unsafe, fixed, stackalloc
/// </summary>
unsafe class UnsafeCodeDemo // unsafe: 允许不安全代码
{
public void DemonstrateUnsafe()
{
Console.WriteLine("\n========== 10. 不安全代码 ==========");
Console.WriteLine("注意:不安全代码需要在项目属性中启用");
// stackalloc: 在栈上分配内存(比堆分配更快)
int* numbers = stackalloc int[5];
for (int i = 0; i < 5; i++)
{
numbers[i] = i * 10;
}
Console.Write("stackalloc 数组: ");
for (int i = 0; i < 5; i++)
{
Console.Write($"{numbers[i]} ");
}
Console.WriteLine();
// 指针操作
int value = 100;
int* ptr = &value;
Console.WriteLine($"指针操作: value = {value}, *ptr = {*ptr}");
*ptr = 200;
Console.WriteLine($"修改指针后: value = {value}");
// fixed: 固定变量地址,防止垃圾回收移动
string text = "Hello";
fixed (char* p = text)
{
Console.WriteLine($"fixed: 字符串 '{text}' 的第一个字符: {*p}");
}
// sizeof: 获取类型大小(不安全上下文)
Console.WriteLine($"sizeof(int): {sizeof(int)} 字节");
Console.WriteLine($"sizeof(bool): {sizeof(bool)} 字节");
Console.WriteLine($"sizeof(decimal): {sizeof(decimal)} 字节");
}
}
#endregion
#region 11. 上下文关键字演示
/// <summary>
/// 演示 var, dynamic, yield, partial, nameof
/// </summary>
class ContextualKeywordsDemo
{
// var: 隐式类型局部变量(编译时确定)
public void DemonstrateVar()
{
Console.WriteLine("\n========== 11. 上下文关键字 ==========");
var number = 42; // 编译为 int
var text = "Hello"; // 编译为 string
var list = new List<int>(); // 编译为 List<int>
Console.WriteLine($"var number: {number} ({number.GetType()})");
Console.WriteLine($"var text: {text} ({text.GetType()})");
Console.WriteLine($"var list: {list.GetType()}");
}
// dynamic: 动态类型(运行时解析)
public void DemonstrateDynamic()
{
dynamic dyn = "Hello";
Console.WriteLine($"dynamic as string: {dyn.Length}"); // 运行时解析
dyn = 123;
Console.WriteLine($"dynamic as int: {dyn + 100}"); // 运行时解析
dyn = new { Name = "动态对象", Value = 999 };
Console.WriteLine($"dynamic as anonymous: {dyn.Name}");
// dynamic 可以调用不存在的方法(运行时才报错)
try
{
dyn.NonExistentMethod(); // 编译通过,运行时抛出异常
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine($"动态调用失败: {ex.Message}");
}
}
// yield: 迭代器
public void DemonstrateYield()
{
Console.WriteLine("\nyield 迭代器演示:");
foreach (var num in GetEvenNumbers(10))
{
Console.Write($"{num} ");
}
Console.WriteLine();
}
private IEnumerable<int> GetEvenNumbers(int max)
{
for (int i = 0; i <= max; i++)
{
if (i % 2 == 0)
{
yield return i; // 返回一个元素并保持状态
}
}
yield break; // 终止迭代
}
// partial: 部分类
partial class PartialClassDemo
{
public void Method1() => Console.WriteLine("Partial Method 1");
}
partial class PartialClassDemo
{
public void Method2() => Console.WriteLine("Partial Method 2");
}
// nameof: 获取名称字符串(编译时)
public void DemonstrateNameof()
{
string varName = nameof(DemonstrateNameof);
string typeName = nameof(PartialClassDemo);
string methodName = nameof(Method1);
Console.WriteLine($"nameof 演示:");
Console.WriteLine($" 方法名: {varName}");
Console.WriteLine($" 类型名: {typeName}");
Console.WriteLine($" 成员名: {methodName}");
}
public void RunPartialDemo()
{
var demo = new PartialClassDemo();
demo.Method1();
demo.Method2();
}
}
#endregion
#region 12. 综合演示
/// <summary>
/// 主程序入口,演示所有特性
/// </summary>
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("╔════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ C# 关键字完全指南 - 综合示例 ║");
Console.WriteLine("╚════════════════════════════════════════════════════════════╝");
// 1. 类型关键字
new TypeKeywordsDemo().DemonstrateTypes();
// 2. 访问修饰符
new AccessModifiersDemo().ShowAccessibleFields();
new DerivedClass().ShowDerivedAccess();
// 3. 类成员修饰符
Animal dog = new Dog { Name = "旺财" };
Animal cat = new Cat { Name = "咪咪" };
dog.MakeSound();
dog.Eat();
cat.MakeSound();
cat.Eat();
var staticDemo = new StaticConstReadonlyDemo(100);
staticDemo.Demonstrate();
new StaticConstReadonlyDemo(200).Demonstrate();
// 4. 控制流语句
new ControlFlowDemo().DemonstrateAll();
// 5. 异常处理
new ExceptionHandlingDemo().DemonstrateExceptions();
// 6. LINQ
new LinqKeywordsDemo().DemonstrateLinq();
// 7. 异步编程
await new AsyncProgrammingDemo().DemonstrateAsync();
// 8. 属性访问器
var propertyDemo = new PropertyAccessorsDemo("user@example.com", "ID-001")
{
Name = "张三",
Age = 30
};
propertyDemo.Demonstrate();
// 9. 泛型约束
new GenericConstraintsDemo().Demonstrate();
// 10. 不安全代码(需要启用unsafe编译选项)
try
{
new UnsafeCodeDemo().DemonstrateUnsafe();
}
catch (Exception ex)
{
Console.WriteLine($"不安全代码演示需要编译选项 /unsafe: {ex.Message}");
}
// 11. 上下文关键字
var contextDemo = new ContextualKeywordsDemo();
contextDemo.DemonstrateVar();
contextDemo.DemonstrateDynamic();
contextDemo.DemonstrateYield();
contextDemo.DemonstrateNameof();
contextDemo.RunPartialDemo();
Console.WriteLine("\n════════════════════════════════════════════════════════════");
Console.WriteLine("所有演示完成!按任意键退出...");
Console.ReadKey();
}
}
#endregion
}