| 变量声明与初始化 |
int num = 10; string str = "hello"; auto list = vector<int>(); |
int num = 10; string str = "hello"; var list = new List<int>(); |
| 条件语句(if-else) |
if (num > 0) { cout << "正数" << endl; } else { cout << "负数" << endl; } |
if (num > 0) { Console.WriteLine("正数"); } else { Console.WriteLine("负数"); } |
| 条件语句(switch) |
switch (str) { case "hello": cout << "你好" << endl; break; } |
switch (str) { case "hello": Console.WriteLine("你好"); break; } |
| 循环语句(for) |
for (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); } |
| 循环语句(while) |
while (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-catch) |
try { throw runtime_error("错误"); } catch (const runtime_error& e) { cout << e.what(); } |
try { throw new Exception("错误"); } catch (Exception ex) { Console.WriteLine(ex.Message); } |
| 委托 / 函数指针 |
function<int(int, int)> add = [](int x, int y) { return x + y; }; |
delegate int Calculate(int a, int b); Calculate add = (x, y) => x + y; |
| 异步编程 |
// C++20 coroutine 需手动实现 |
public async Task<int> GetDataAsync() { await Task.Delay(1000); return 100; } |