C# 基础语法(自用记录)

35 阅读3分钟

C# 语法体系完整概览

1. 基础语法结构

程序结构

using System;  // 引入命名空间

namespace HelloWorld  // 命名空间声明
{
    class Program  // 类声明
    {
        static void Main(string[] args)  // 主方法
        {
            Console.WriteLine("Hello, World!");  // 语句
        }
    }
}

注释

// 单行注释

/*
 多行注释
 可以跨越多行
*/

/// <summary>
/// XML 文档注释
/// </summary>
public class MyClass { }

2. 数据类型

值类型

// 基本类型
bool isActive = true;           // 布尔型
byte byteValue = 255;           // 字节
char letter = 'A';              // 字符
int number = 42;                // 整数
long bigNumber = 1000000L;      // 长整数
float price = 19.99f;           // 单精度浮点数
double distance = 123.45;       // 双精度浮点数
decimal money = 999.99m;        // 十进制数

// 结构体
struct Point
{
    public int X;
    public int Y;
    
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

// 枚举
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
enum Status { Active = 1, Inactive = 0, Pending = 2 }

引用类型

// 字符串
string name = "John";
string message = $"Hello, {name}";  // 字符串插值
string path = @"C:\Users\John";     // 逐字字符串

// 数组
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
int[,] matrix = new int[2, 3];  // 多维数组
int[][] jaggedArray = new int[3][];  // 交错数组

// 对象
object obj = new object();

可空类型

int? nullableInt = null;           // 可空整数
Nullable<double> nullableDouble = 3.14;  // 另一种写法
bool? nullableBool = true;

// 空合并运算符
int actualValue = nullableInt ?? 0;  // 如果为null则返回0
string result = name ?? "Unknown";

3. 变量与常量

// 变量声明
int age = 25;
var name = "John";        // 隐式类型
dynamic dynamicVar = 10;  // 动态类型

// 常量
const double PI = 3.14159;
const string AppName = "MyApp";

// 只读变量
readonly int MaxCount = 100;

// 元组
(string, int) person = ("John", 25);
var person2 = (Name: "John", Age: 25);  // 命名元组

4. 运算符

// 算术运算符
int a = 10 + 5;  // 15
int b = 10 - 5;  // 5
int c = 10 * 5;  // 50
int d = 10 / 5;  // 2
int e = 10 % 3;  // 1

// 比较运算符
bool f = (10 == 5);  // false
bool g = (10 != 5);  // true
bool h = (10 > 5);   // true
bool i = (10 < 5);   // false

// 逻辑运算符
bool j = (true && false);  // false - AND
bool k = (true || false);  // true - OR
bool l = !true;            // false - NOT

// 位运算符
int m = 5 & 3;   // 1 - AND
int n = 5 | 3;   // 7 - OR
int o = 5 ^ 3;   // 6 - XOR
int p = ~5;      // -6 - 取反
int q = 5 << 1;  // 10 - 左移
int r = 5 >> 1;  // 2 - 右移

// 赋值运算符
int s = 10;
s += 5;    // s = 15
s -= 3;    // s = 12
s *= 2;    // s = 24

// 空条件运算符
string text = null;
int? length = text?.Length;  // null,不会抛出异常
string firstChar = text?[0].ToString();  // null

// 空合并运算符
string name2 = null;
string displayName = name2 ?? "Anonymous";  // "Anonymous"

// 范围运算符
int[] numbers2 = { 0, 1, 2, 3, 4, 5 };
var slice1 = numbers2[1..4];    // [1, 2, 3]
var slice2 = numbers2[..3];     // [0, 1, 2]
var slice3 = numbers2[3..];     // [3, 4, 5]
var slice4 = numbers2[^2..];    // [4, 5] - 从末尾开始

5. 流程控制

条件语句

// if-else
int score = 85;
if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 80)
{
    Console.WriteLine("良好");
}
else
{
    Console.WriteLine("继续努力");
}

// switch 语句 (传统)
int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("星期一");
        break;
    case 2:
        Console.WriteLine("星期二");
        break;
    default:
        Console.WriteLine("其他日子");
        break;
}

// switch 表达式 (C# 8.0+)
string dayName = day switch
{
    1 => "星期一",
    2 => "星期二",
    3 => "星期三",
    _ => "其他日子"
};

// 模式匹配
object obj = "Hello";
if (obj is string str && str.Length > 0)
{
    Console.WriteLine($"字符串长度: {str.Length}");
}

循环语句

// for 循环
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// foreach 循环
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

// while 循环
int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

// do-while 循环
int number = 0;
do
{
    Console.WriteLine(number);
    number++;
} while (number < 5);

跳转语句

// break
for (int i = 0; i < 10; i++)
{
    if (i == 5) break;
    Console.WriteLine(i);
}

// continue
for (int i = 0; i < 5; i++)
{
    if (i == 2) continue;
    Console.WriteLine(i);
}

// return
int Add(int a, int b)
{
    return a + b;
}

// goto (不推荐使用)
for (int i = 0; i < 10; i++)
{
    if (i == 5) goto Found;
}
Found:
Console.WriteLine("找到5了");

6. 面向对象编程

类与对象

// 基本类定义
public class Person
{
    // 字段
    private string name;
    private int age;
    
    // 属性
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    
    // 自动属性
    public int Age { get; set; }
    
    // 构造函数
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // 方法
    public void Introduce()
    {
        Console.WriteLine($"我叫{Name},今年{Age}岁");
    }
    
    // 静态方法
    public static void SayHello()
    {
        Console.WriteLine("Hello!");
    }
}

// 使用
Person person = new Person("John", 25);
person.Introduce();
Person.SayHello();

继承与多态

// 基类
public class Animal
{
    public string Name { get; set; }
    
    public virtual void Speak()
    {
        Console.WriteLine("动物叫");
    }
}

// 派生类
public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("汪汪!");
    }
}

public class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine("喵喵!");
    }
    
    // 新方法
    public void Climb()
    {
        Console.WriteLine("爬树");
    }
}

// 使用多态
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.Speak();  // 汪汪!
myCat.Speak();  // 喵喵!

抽象类与接口

// 抽象类
public abstract class Shape
{
    public abstract double CalculateArea();
    
    public void Display()
    {
        Console.WriteLine($"面积: {CalculateArea()}");
    }
}

// 接口
public interface IDrawable
{
    void Draw();
}

public interface IResizable
{
    void Resize(double factor);
}

// 实现
public class Circle : Shape, IDrawable, IResizable
{
    public double Radius { get; set; }
    
    public override double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
    
    public void Draw()
    {
        Console.WriteLine("绘制圆形");
    }
    
    public void Resize(double factor)
    {
        Radius *= factor;
    }
}

访问修饰符

public class AccessExample
{
    public string PublicMember;       // 任何地方可访问
    private string PrivateMember;     // 仅本类可访问
    protected string ProtectedMember; // 本类及派生类可访问
    internal string InternalMember;   // 同一程序集可访问
    protected internal string ProtectedInternalMember; // 同一程序集或派生类
}

7. 高级特性

泛型

// 泛型类
public class GenericList<T>
{
    private T[] items;
    private int count;
    
    public GenericList(int capacity)
    {
        items = new T[capacity];
    }
    
    public void Add(T item)
    {
        items[count++] = item;
    }
    
    public T Get(int index)
    {
        return items[index];
    }
}

// 泛型方法
public T Max<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b) > 0 ? a : b;
}

// 使用
GenericList<string> stringList = new GenericList<string>(10);
stringList.Add("Hello");
GenericList<int> intList = new GenericList<int>(10);
intList.Add(42);

委托与事件

// 委托定义
public delegate void MessageHandler(string message);

public class Publisher
{
    // 事件定义
    public event MessageHandler MessageReceived;
    
    public void SendMessage(string message)
    {
        MessageReceived?.Invoke(message);
    }
}

public class Subscriber
{
    public void OnMessageReceived(string message)
    {
        Console.WriteLine($"收到消息: {message}");
    }
}

// 使用
var publisher = new Publisher();
var subscriber = new Subscriber();

publisher.MessageReceived += subscriber.OnMessageReceived;
publisher.SendMessage("Hello Event!");

Lambda 表达式

// 匿名方法
Func<int, int, int> add = delegate(int a, int b) { return a + b; };

// Lambda 表达式
Func<int, int, int> multiply = (a, b) => a * b;
Func<int, bool> isEven = x => x % 2 == 0;
Action<string> print = message => Console.WriteLine(message);

// 使用 LINQ
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);

8. 异常处理

try
{
    // 可能抛出异常的代码
    int result = Divide(10, 0);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"除零错误: {ex.Message}");
}
catch (ArgumentException ex)
{
    Console.WriteLine($"参数错误: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"其他错误: {ex.Message}");
}
finally
{
    Console.WriteLine("无论是否异常都会执行");
}

int Divide(int a, int b)
{
    if (b == 0)
        throw new DivideByZeroException("除数不能为零");
    return a / b;
}

9. 异步编程

// async/await
public async Task<string> DownloadDataAsync(string url)
{
    using (var client = new HttpClient())
    {
        try
        {
            return await client.GetStringAsync(url);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"下载失败: {ex.Message}");
            return null;
        }
    }
}

// 使用
public async Task ProcessData()
{
    string data = await DownloadDataAsync("https://example.com");
    if (data != null)
    {
        Console.WriteLine($"数据长度: {data.Length}");
    }
}

// 并行处理
public async Task ProcessMultipleUrls()
{
    var urls = new[] { "url1", "url2", "url3" };
    var tasks = urls.Select(url => DownloadDataAsync(url));
    string[] results = await Task.WhenAll(tasks);
}

10. LINQ (语言集成查询)

var people = new List<Person>
{
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 35)
};

// 查询语法
var query1 = from p in people
            where p.Age > 25
            orderby p.Name
            select p.Name;

// 方法语法
var query2 = people
    .Where(p => p.Age > 25)
    .OrderBy(p => p.Name)
    .Select(p => p.Name);

// 分组
var grouped = from p in people
             group p by p.Age into ageGroup
             select new { Age = ageGroup.Key, Count = ageGroup.Count() };

// 连接
var joined = from p in people
            join a in addresses on p.Id equals a.PersonId
            select new { p.Name, a.City };

11. 现代 C# 特性 (C# 8.0-11.0)

记录类型 (C# 9.0+)

// 记录类 - 不可变,值语义
public record PersonRecord(string Name, int Age);

// 使用
var person1 = new PersonRecord("John", 25);
var person2 = person1 with { Age = 26 };  // 非破坏性修改

// 模式匹配增强
var result = person1 switch
{
    PersonRecord("John", _) => "这是John",
    PersonRecord(_, > 18) => "成年人",
    _ => "其他"
};

顶级语句 (C# 9.0+)

// 不需要 Main 方法,直接写代码
using System;

Console.WriteLine("Hello, World!");
return 0;  // 可选的返回值

全局 using (C# 10.0+)

// GlobalUsings.cs
global using System;
global using System.Collections.Generic;
// 然后在任何文件都不需要再写 using