C# 语法体系完整概览
1. 基础语法结构
程序结构
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
注释
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;
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;
int b = 10 - 5;
int c = 10 * 5;
int d = 10 / 5;
int e = 10 % 3;
bool f = (10 == 5);
bool g = (10 != 5);
bool h = (10 > 5);
bool i = (10 < 5);
bool j = (true && false);
bool k = (true || false);
bool l = !true;
int m = 5 & 3;
int n = 5 | 3;
int o = 5 ^ 3;
int p = ~5;
int q = 5 << 1;
int r = 5 >> 1;
int s = 10;
s += 5;
s -= 3;
s *= 2;
string text = null;
int? length = text?.Length;
string firstChar = text?[0].ToString();
string name2 = null;
string displayName = name2 ?? "Anonymous";
int[] numbers2 = { 0, 1, 2, 3, 4, 5 };
var slice1 = numbers2[1..4];
var slice2 = numbers2[..3];
var slice3 = numbers2[3..];
var slice4 = numbers2[^2..];
5. 流程控制
条件语句
int score = 85;
if (score >= 90)
{
Console.WriteLine("优秀");
}
else if (score >= 80)
{
Console.WriteLine("良好");
}
else
{
Console.WriteLine("继续努力");
}
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("星期一");
break;
case 2:
Console.WriteLine("星期二");
break;
default:
Console.WriteLine("其他日子");
break;
}
string dayName = day switch
{
1 => "星期一",
2 => "星期二",
3 => "星期三",
_ => "其他日子"
};
object obj = "Hello";
if (obj is string str && str.Length > 0)
{
Console.WriteLine($"字符串长度: {str.Length}");
}
循环语句
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
Console.WriteLine(name);
}
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
int number = 0;
do
{
Console.WriteLine(number);
number++;
} while (number < 5);
跳转语句
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
Console.WriteLine(i);
}
for (int i = 0; i < 5; i++)
{
if (i == 2) continue;
Console.WriteLine(i);
}
int Add(int a, int b)
{
return a + b;
}
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; };
Func<int, int, int> multiply = (a, b) => a * b;
Func<int, bool> isEven = x => x % 2 == 0;
Action<string> print = message => Console.WriteLine(message);
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. 异步编程
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+)
using System;
Console.WriteLine("Hello, World!");
return 0;
全局 using (C# 10.0+)
global using System;
global using System.Collections.Generic;