C++、C#常用语法对比
对比项C 实现示例C# 实现示例变量声明与初始化int num 10; string str hello; auto list vectorint();int num 10; string str hello; var list new Listint();条件语句if-elseif (num 0) { cout 正数 endl; } else { cout 负数 endl; }if (num 0) { Console.WriteLine(正数); } else { Console.WriteLine(负数); }条件语句switchswitch (str) { case hello: cout 你好 endl; break; }switch (str) { case hello: Console.WriteLine(你好); break; }循环语句forfor (int i 0; i 5; i) { cout i endl; }for (int i 0; i 5; i) { Console.WriteLine(i); }循环语句遍历集合for (auto item : list) { cout item endl; }foreach (var item in list) { Console.WriteLine(item); }循环语句whilewhile (num 0) num--;while (num 0) num--;类定义class Person { private: string name; public: Person(string n) : name(n) {} }class Person { public string Name { get; set; } public Person(string name) { Name name; } }继承class Student : public Person { public: Student(string n) : Person(n) {} }class Student : Person { public Student(string name) : base(name) {} }方法重写void SayHello() override { cout Hello endl; }public override void SayHello() { Console.WriteLine(Hello); }内存分配栈Person p1(Tom);int age 20;内存分配堆Person* p2 new Person(Jerry); delete p2;Person p1 new Person(Tom);空值处理string* str nullptr; string name (str ! nullptr) ? *str : 默认值;string str null; string name str ?? 默认值;异常处理try-catchtry { throw runtime_error(错误); } catch (const runtime_error e) { cout e.what(); }try { throw new Exception(错误); } catch (Exception ex) { Console.WriteLine(ex.Message); }委托 / 函数指针functionint(int, int) add [](int x, int y) { return x y; };delegate int Calculate(int a, int b); Calculate add (x, y) x y;异步编程// C20 coroutine 需手动实现public async Taskint GetDataAsync() { await Task.Delay(1000); return 100; }总结核心语法结构循环、条件两者相似C# 新增foreach、var等语法糖C 依赖auto、范围 for。面向对象层面C 支持多继承、手动封装字段C# 仅单继承、内置属性封装。内存 / 空值处理C 需手动管理堆内存、判断指针空值C# 依赖 GC 和空安全运算符。