C#基础详解
一、C#语言概述
C#(读作"C Sharp")是微软开发的面向对象的编程语言,运行在.NET平台上。它结合了C++的强大功能和Visual Basic的简单性,具有以下特点:
- 面向对象:支持封装、继承和多态
- 类型安全:编译时类型检查
- 自动内存管理:通过垃圾回收器(GC)管理内存
- 跨平台:通过.NET Core/.NET 5+支持多平台
- 丰富的标准库:提供大量内置类和功能
二、基本语法
1. 变量与数据类型
// 声明变量
int age = 25;
double price = 19.99;
char grade = 'A';
bool isActive = true;
string name = "张三";
// 变量类型
byte b = 255; // 0-255
sbyte sb = -128; // -128到127
short s = 32767; // -32,768到32,767
ushort us = 65535; // 0到65,535
int i = 2147483647; // -2^31到2^31-1
uint ui = 4294967295; // 0到2^32-1
long l = 9223372036854775807; // -2^63到2^63-1
ulong ul = 18446744073709551615; // 0到2^64-1
float f = 3.14f; // 单精度浮点数
decimal d = 123.45m; // 高精度十进制数
2. 运算符
// 算术运算符
int sum = 5 + 3; // 8
int diff = 5 - 3; // 2
int prod = 5 * 3; // 15
int quot = 5 / 2; // 2 (整数除法)
int rem = 5 % 2; // 1 (余数)
// 关系运算符
bool isEqual = 5 == 5; // true
bool isNotEqual = 5 != 3; // true
bool isGreater = 5 > 3; // true
// 逻辑运算符
bool result = (5 > 3) && (2 < 4); // true
bool result2 = (5 > 3) || (2 > 4); // true
bool notResult = !(5 > 3); // false
3. 控制结构
// 条件语句
if (age >= 18)
{
Console.WriteLine("成年人");
}
else if (age >= 13)
{
Console.WriteLine("青少年");
}
else
{
Console.WriteLine("儿童");
}
// switch语句
switch (grade)
{
case 'A':
Console.WriteLine("优秀");
break;
case 'B':
Console.WriteLine("良好");
break;
default:
Console.WriteLine("其他");
break;
}
// 循环
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
int j = 0;
while (j < 5)
{
Console.WriteLine(j);
j++;
}
int k = 0;
do
{
Console.WriteLine(k);
k++;
} while (k < 5);
// foreach循环
string[] fruits = { "苹果", "香蕉", "橙子" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
三、面向对象编程
1. 类与对象
// 定义类
public class Person
{
// 字段
private string name;
private int age;
// 属性
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set
{
if (value >= 0)
age = value;
}
}
// 构造函数
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// 方法
public void Introduce()
{
Console.WriteLine($"我叫{this.name},今年{this.age}岁。");
}
}
// 使用类
Person person = new Person("张三", 25);
person.Introduce();
2. 继承与多态
// 基类
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("动物发出声音");
}
}
// 派生类
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("汪汪叫");
}
// 新增方法
public void Fetch()
{
Console.WriteLine("接球");
}
}
// 使用继承
Animal myAnimal = new Dog();
myAnimal.MakeSound(); // 输出"汪汪叫" (多态)
// 类型检查与转换
if (myAnimal is Dog)
{
Dog myDog = (Dog)myAnimal;
myDog.Fetch();
}
3. 接口
// 定义接口
public interface IShape
{
double GetArea();
double GetPerimeter();
}
// 实现接口
public class Circle : IShape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public double GetArea()
{
return Math.PI * Radius * Radius;
}
public double GetPerimeter()
{
return 2 * Math.PI * Radius;
}
}
// 使用接口
IShape shape = new Circle(5);
Console.WriteLine($"面积: {shape.GetArea()}");
四、集合与泛型
1. 内置集合
// 数组
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // 输出1
// List
List<string> fruits = new List<string>();
fruits.Add("苹果");
fruits.Add("香蕉");
Console.WriteLine(fruits.Count); // 输出2
// Dictionary
Dictionary<string, int> ageDict = new Dictionary<string, int>();
ageDict.Add("张三", 25);
ageDict["李四"] = 30;
Console.WriteLine(ageDict["张三"]); // 输出25
// Queue
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
Console.WriteLine(queue.Dequeue()); // 输出1
// Stack
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
Console.WriteLine(stack.Pop()); // 输出2
2. 泛型集合
// 泛型List
List<int> intList = new List<int> { 1, 2, 3 };
intList.Add(4);
foreach (int num in intList)
{
Console.WriteLine(num);
}
// 泛型Dictionary
Dictionary<string, Person> people = new Dictionary<string, Person>();
people.Add("P1", new Person("张三", 25));
Person p = people["P1"];
Console.WriteLine(p.Name);
// 泛型约束
public class Box<T> where T : IComparable
{
public T Value { get; set; }
public bool IsGreaterThan(Box<T> other)
{
return Value.CompareTo(other.Value) > 0;
}
}
五、委托与事件
1. 委托
// 定义委托
public delegate void PrintDelegate(string message);
// 使用委托
public class Printer
{
public static void PrintToConsole(string message)
{
Console.WriteLine(message);
}
}
PrintDelegate print = new PrintDelegate(Printer.PrintToConsole);
print("Hello, World!");
// 多播委托
PrintDelegate multiPrint = print;
multiPrint += (msg) => Console.WriteLine($"日志: {msg}");
multiPrint("测试多播");
2. 事件
// 定义事件参数
public class TemperatureChangedEventArgs : EventArgs
{
public double OldTemperature { get; }
public double NewTemperature { get; }
public TemperatureChangedEventArgs(double oldTemp, double newTemp)
{
OldTemperature = oldTemp;
NewTemperature = newTemp;
}
}
// 定义事件发布者
public class TemperatureSensor
{
// 定义事件
public event EventHandler<TemperatureChangedEventArgs> TemperatureChanged;
private double currentTemperature;
public double CurrentTemperature
{
get => currentTemperature;
set
{
if (currentTemperature != value)
{
double oldTemp = currentTemperature;
currentTemperature = value;
// 触发事件
TemperatureChanged?.Invoke(this,
new TemperatureChangedEventArgs(oldTemp, currentTemperature));
}
}
}
}
// 使用事件
public class TemperatureMonitor
{
public TemperatureMonitor(TemperatureSensor sensor)
{
sensor.TemperatureChanged += OnTemperatureChanged;
}
private void OnTemperatureChanged(object sender, TemperatureChangedEventArgs e)
{
Console.WriteLine($"温度从 {e.OldTemperature}°C 变为 {e.NewTemperature}°C");
}
}
六、异常处理
try
{
// 可能抛出异常的代码
int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
// 处理特定异常
Console.WriteLine($"除零错误: {ex.Message}");
}
catch (FormatException ex)
{
// 处理格式错误
Console.WriteLine($"格式错误: {ex.Message}");
}
catch (Exception ex) // 基类异常
{
// 处理其他所有异常
Console.WriteLine($"发生错误: {ex.Message}");
}
finally
{
// 无论是否发生异常都会执行的代码
Console.WriteLine("执行完毕");
}
// 抛出异常
throw new InvalidOperationException("无效操作");
七、LINQ查询
// 数据源
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 查询表达式
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// 方法语法
var oddNumbers = numbers.Where(n => n % 2 != 0)
.OrderByDescending(n => n)
.Take(3);
// 查询结果
foreach (int num in evenNumbers)
{
Console.WriteLine(num);
}
// 延迟执行示例
var query = numbers.Where(n => n > 5); // 不立即执行
numbers.Add(11); // 修改数据源
foreach (int num in query) // 此时才执行查询
{
Console.WriteLine(num); // 会包含11
}
八、异步编程
// 异步方法
public async Task<string> DownloadDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
// 异步等待
string data = await client.GetStringAsync(url);
return data;
}
}
// 使用异步方法
public async Task ProcessDataAsync()
{
try
{
Console.WriteLine("开始下载...");
string result = await DownloadDataAsync("https://example.com");
Console.WriteLine($"下载完成: {result.Length} 字符");
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
// 并行处理
public void ProcessInParallel()
{
List<int> numbers = Enumerable.Range(1, 1000).ToList();
// 并行处理
Parallel.ForEach(numbers, num =>
{
// 处理每个数字
int square = num * num;
Console.WriteLine($"计算 {num} 的平方: {square}");
});
}
九、文件与流操作
// 写入文件
string filePath = "test.txt";
File.WriteAllText(filePath, "Hello, World!");
// 读取文件
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
// 逐行读取
foreach (string line in File.ReadLines(filePath))
{
Console.WriteLine(line);
}
// 使用流
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
byte[] data = Encoding.UTF8.GetBytes("二进制数据");
fs.Write(data, 0, data.Length);
}
// 读写JSON
var person = new { Name = "张三", Age = 25 };
string json = JsonConvert.SerializeObject(person);
File.WriteAllText("person.json", json);
string jsonContent = File.ReadAllText("person.json");
var deserializedPerson = JsonConvert.DeserializeObject(jsonContent);
十、常用设计模式
1. 单例模式
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
2. 工厂模式
// 产品接口
public interface IProduct
{
void Operation();
}
// 具体产品
public class ConcreteProductA : IProduct
{
public void Operation() => Console.WriteLine("产品A操作");
}
public class ConcreteProductB : IProduct
{
public void Operation() => Console.WriteLine("产品B操作");
}
// 工厂接口
public interface IFactory
{
IProduct CreateProduct();
}
// 具体工厂
public class ConcreteFactoryA : IFactory
{
public IProduct CreateProduct() => new ConcreteProductA();
}
public class ConcreteFactoryB : IFactory
{
public IProduct CreateProduct() => new ConcreteProductB();
}
3. 观察者模式
// 主题接口
public interface ISubject
{
void RegisterObserver(IObserver o);
void RemoveObserver(IObserver o);
void NotifyObservers();
}
// 观察者接口
public interface IObserver
{
void Update(string message);
}
// 具体主题
public class ConcreteSubject : ISubject
{
private List<IObserver> observers = new List<IObserver>();
private string message;
public void RegisterObserver(IObserver o) => observers.Add(o);
public void RemoveObserver(IObserver o) => observers.Remove(o);
public void NotifyObservers()
{
foreach (var observer in observers)
{
observer.Update(message);
}
}
public void SetMessage(string msg)
{
message = msg;
NotifyObservers();
}
}
// 具体观察者
public class ConcreteObserver : IObserver
{
private string name;
public ConcreteObserver(string name) => this.name = name;
public void Update(string message)
{
Console.WriteLine($"{name} 收到消息: {message}");
}
}
十一、性能优化技巧
-
字符串处理:
// 避免频繁创建字符串 StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.Append(i); } string result = sb.ToString(); // 字符串比较 string a = "hello"; string b = "HELLO"; bool equal = string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
-
集合操作:
// 使用泛型集合 List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // 避免装箱/拆箱 HashSet<int> intSet = new HashSet<int>(); // 使用LINQ时考虑性能 var query = numbers.Where(n => n > 2).ToList(); // 立即执行
-
内存管理:
// 及时释放资源 using (var stream = new FileStream("file.txt", FileMode.Open)) { // 使用stream } // 自动调用Dispose() // 对于实现了IDisposable的对象 var disposableObj = new SomeDisposableObject(); try { // 使用对象 } finally { disposableObj.Dispose(); }
-
异步编程:
// 避免async void方法(除了事件处理) public async Task ProcessAsync() { await Task.Delay(1000); } // 并行处理大数据集 Parallel.For(0, 1000, i => { // 处理每个元素 });
十二、调试与诊断
-
断点调试:
- 在代码行号左侧点击设置断点
- 使用F5启动调试
- 使用F10单步执行,F11进入方法
-
监视窗口:
- 添加变量到监视窗口
- 查看表达式值
- 条件断点设置
-
性能分析:
// 使用Stopwatch测量代码执行时间 var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // 要测量的代码 stopwatch.Stop(); Console.WriteLine($"耗时: {stopwatch.ElapsedMilliseconds} 毫秒"); // 内存分析 long memoryBefore = GC.GetTotalMemory(false); // 分配内存的代码 long memoryAfter = GC.GetTotalMemory(false); Console.WriteLine($"内存使用: {(memoryAfter - memoryBefore)/1024} KB");
-
日志记录:
// 使用内置日志记录 System.Diagnostics.Trace.WriteLine("调试信息"); System.Diagnostics.Debug.WriteLine("调试信息(仅在Debug模式下)"); // 使用NLog或Serilog等日志框架 // 需要先安装NuGet包 // logger.Info("应用程序启动");
十三、进阶主题
-
反射:
// 获取类型信息 Type type = typeof(string); Console.WriteLine($"类型名: {type.Name}"); // 创建实例 object instance = Activator.CreateInstance(type); // 调用方法 MethodInfo method = type.GetMethod("Substring", new[] { typeof(int), typeof(int) }); string result = (string)method.Invoke("Hello, World!", new object[] { 0, 5 }); Console.WriteLine(result); // 输出"Hello"
-
动态编程:
// 使用dynamic dynamic obj = new ExpandoObject(); obj.Name = "张三"; obj.Age = 25; Console.WriteLine($"{obj.Name}今年{obj.Age}岁"); // 动态方法调用 var calculator = new ExpandoObject() as IDictionary<string, object>; calculator["Add"] = new Func<int, int, int>((a, b) => a + b); int sum = (int)calculator["Add"](3, 5); Console.WriteLine(sum); // 输出8
-
并行编程:
// 使用Parallel类 Parallel.For(0, 100, i => { // 并行处理每个i }); // 使用Task并行 Task t1 = Task.Run(() => ProcessData1()); Task t2 = Task.Run(() => ProcessData2()); await Task.WhenAll(t1, t2); // 数据并行 var numbers = Enumerable.Range(1, 1000).ToList(); var parallelResult = numbers.AsParallel() .Where(n => n % 2 == 0) .OrderBy(n => n) .Take(10) .ToList();
-
异步流(.NET Core 3.0+):
// 异步生成器 public async IAsyncEnumerable<int> GenerateNumbersAsync() { for (int i = 0; i < 10; i++) { await Task.Delay(100); yield return i; } } // 使用异步流 await foreach (var number in GenerateNumbersAsync()) { Console.WriteLine(number); }
十四、最佳实践
-
命名规范:
- 类名使用PascalCase(如
CustomerService
) - 方法名使用PascalCase(如
GetCustomerData
) - 变量名使用camelCase(如
customerName
) - 常量使用PASCAL_CASE(如
MAX_RETRIES
)
- 类名使用PascalCase(如
-
代码组织:
- 按功能而非类型组织代码文件
- 使用区域(Regions)组织大型类
- 保持方法简短(建议不超过20行)
-
异常处理:
- 捕获特定异常而非通用Exception
- 不要捕获不处理的异常
- 在适当位置记录异常
-
性能考虑:
- 避免在循环中分配内存
- 使用StringBuilder处理大量字符串操作
- 考虑对象池重用对象
-
安全性:
- 验证所有输入数据
- 使用参数化查询防止SQL注入
- 对敏感数据进行加密
-
测试:
- 编写单元测试覆盖核心逻辑
- 使用Mock对象隔离依赖
- 定期进行代码审查
通过掌握这些C#基础知识和进阶技术,您可以构建高效、可维护的.NET应用程序。记住,良好的编码习惯和持续学习是成为优秀开发者的关键。