C# 标准库详解 什么是 C# 标准库? C# 标准库是 .NET 平台的核心组成部分,提供了丰富的类和方法,用于开发各种类型的应用程序。它包含在 .NET Framework、.NET Core 和 .NET 5+ 中,为 C# 程序员提供了强大的工具集。
C# 标准库的组成 C# 标准库主要由以下几个部分组成:
基础类型库 :提供基本数据类型和通用工具
集合库 :提供各种数据结构
IO 库 :处理文件和流操作
网络库 :提供网络通信功能
多线程库 :支持并发编程
反射库 :提供类型信息和动态操作
序列化库 :支持对象的序列化和反序列化
加密库 :提供安全加密功能
正则表达式库 :处理字符串模式匹配
XML 库 :处理 XML 数据
LINQ :语言集成查询
任务并行库 :高级并行编程
WPF/WinForms :GUI 开发(仅限 Windows)
常用库的详细介绍 1. 基础类型库 基础类型库位于 System 命名空间,提供了基本数据类型和通用工具类。
常用类和方法
类/方法
功能
使用示例
Object
所有类型的基类
object obj = new object();
String
字符串操作
string s = "Hello";
DateTime
日期时间处理
DateTime now = DateTime.Now;
Math
数学运算
double pi = Math.PI;
Convert
类型转换
int i = Convert.ToInt32("123");
Console
控制台操作
Console.WriteLine("Hello World");
Random
随机数生成
Random rnd = new Random();
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System;class Program { static void Main () { string s = "Hello, World!" ; Console.WriteLine(s.Length); Console.WriteLine(s.Substring(7 )); Console.WriteLine(s.ToUpper()); DateTime now = DateTime.Now; Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss" )); double x = 3.0 , y = 4.0 ; double hypotenuse = Math.Sqrt(x * x + y * y); Console.WriteLine(hypotenuse); Random rnd = new Random(); Console.WriteLine(rnd.Next(1 , 100 )); } }
2. 集合库 集合库位于 System.Collections 和 System.Collections.Generic 命名空间,提供了各种数据结构。
常用集合类
集合类
功能
使用示例
List<T>
动态数组
List<int> list = new List<int>();
Dictionary<K, V>
键值对集合
Dictionary<string, int> dict = new Dictionary<string, int>();
HashSet<T>
无序唯一元素集合
HashSet<int> set = new HashSet<int>();
Queue<T>
队列(FIFO)
Queue<int> queue = new Queue<int>();
Stack<T>
栈(LIFO)
Stack<int> stack = new Stack<int>();
LinkedList<T>
双向链表
LinkedList<int> linkedList = new LinkedList<int>();
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 using System;using System.Collections.Generic;class Program { static void Main () { List<int > numbers = new List<int >(); numbers.Add(10 ); numbers.Add(20 ); numbers.Add(30 ); Console.WriteLine("List elements:" ); foreach (int num in numbers) { Console.WriteLine(num); } Dictionary<string , string > capitals = new Dictionary<string , string >(); capitals["China" ] = "Beijing" ; capitals["USA" ] = "Washington" ; capitals["Japan" ] = "Tokyo" ; Console.WriteLine("\nDictionary elements:" ); foreach (var pair in capitals) { Console.WriteLine($"{pair.Key} : {pair.Value} " ); } HashSet<int > uniqueNumbers = new HashSet<int >(); uniqueNumbers.Add(1 ); uniqueNumbers.Add(2 ); uniqueNumbers.Add(1 ); Console.WriteLine("\nHashSet elements:" ); foreach (int num in uniqueNumbers) { Console.WriteLine(num); } } }
3. IO 库 IO 库位于 System.IO 命名空间,提供文件和流操作功能。
常用类
类
功能
使用示例
File
文件操作静态方法
File.ReadAllText("file.txt");
Directory
目录操作静态方法
Directory.CreateDirectory("folder");
Path
路径操作静态方法
Path.Combine("dir", "file.txt");
StreamReader
文本文件读取
using (StreamReader sr = new StreamReader("file.txt")) { ... }
StreamWriter
文本文件写入
using (StreamWriter sw = new StreamWriter("file.txt")) { ... }
FileStream
字节流操作
using (FileStream fs = new FileStream("file.bin", FileMode.Open)) { ... }
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 using System;using System.IO;class Program { static void Main () { string filePath = "example.txt" ; File.WriteAllText(filePath, "Hello, C# IO!" ); string content = File.ReadAllText(filePath); Console.WriteLine("File content:" ); Console.WriteLine(content); File.AppendAllText(filePath, "\nAppended text." ); string [] lines = File.ReadAllLines(filePath); Console.WriteLine("\nFile lines:" ); foreach (string line in lines) { Console.WriteLine(line); } File.Delete(filePath); Console.WriteLine($"\nFile exists: {File.Exists(filePath)} " ); } }
4. 网络库 网络库位于 System.Net 和 System.Net.Sockets 命名空间,提供网络通信功能。
常用类
类
功能
使用示例
WebClient
简单的 HTTP 客户端
using (WebClient client = new WebClient()) { ... }
HttpClient
现代 HTTP 客户端
using (HttpClient client = new HttpClient()) { ... }
TcpClient
TCP 客户端
using (TcpClient client = new TcpClient()) { ... }
TcpListener
TCP 服务器
using (TcpListener listener = new TcpListener(port)) { ... }
Socket
底层套接字操作
Socket socket = new Socket(AddressFamily.InterNetwork, ...);
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 using System;using System.Net.Http;using System.Threading.Tasks;class Program { static async Task Main () { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://api.github.com/users/octocat" ); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("GitHub API response:" ); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Error: {e.Message} " ); } } } }
5. 多线程库 多线程库位于 System.Threading 命名空间,提供并发编程功能。
常用类和方法
类/方法
功能
使用示例
Thread
线程操作
Thread thread = new Thread(Work);
Task
异步任务
Task.Run(() => { ... });
ThreadPool
线程池
ThreadPool.QueueUserWorkItem(Work);
Mutex
互斥锁
using (Mutex mutex = new Mutex()) { ... }
Monitor
同步锁
lock (obj) { ... }
Semaphore
信号量
using (Semaphore semaphore = new Semaphore(1, 1)) { ... }
AutoResetEvent
自动重置事件
using (AutoResetEvent evt = new AutoResetEvent(false)) { ... }
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 using System;using System.Threading;using System.Threading.Tasks;class Program { static void Main () { Console.WriteLine("Main thread started" ); Task task1 = Task.Run(() => { for (int i = 0 ; i < 5 ; i++) { Console.WriteLine($"Task 1: {i} " ); Thread.Sleep(100 ); } }); Task task2 = Task.Run(() => { for (int i = 0 ; i < 5 ; i++) { Console.WriteLine($"Task 2: {i} " ); Thread.Sleep(100 ); } }); Task.WaitAll(task1, task2); Console.WriteLine("Main thread completed" ); AsyncExample().Wait(); } static async Task AsyncExample () { Console.WriteLine("\nAsync example started" ); await Task.Delay(1000 ); Console.WriteLine("Async example completed" ); } }
6. 反射库 反射库位于 System.Reflection 命名空间,提供类型信息和动态操作功能。
常用类
类
功能
使用示例
Type
类型信息
Type type = typeof(string);
Assembly
程序集信息
Assembly assembly = Assembly.GetExecutingAssembly();
MethodInfo
方法信息
MethodInfo method = type.GetMethod("ToString");
PropertyInfo
属性信息
PropertyInfo property = type.GetProperty("Length");
Activator
动态创建实例
object obj = Activator.CreateInstance(type);
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 using System;using System.Reflection;class Person { public string Name { get ; set ; } public int Age { get ; set ; } public void SayHello () { Console.WriteLine($"Hello, my name is {Name} !" ); } } class Program { static void Main () { Type personType = typeof (Person); object personObj = Activator.CreateInstance(personType); PropertyInfo nameProperty = personType.GetProperty("Name" ); nameProperty.SetValue(personObj, "John" ); PropertyInfo ageProperty = personType.GetProperty("Age" ); ageProperty.SetValue(personObj, 30 ); MethodInfo sayHelloMethod = personType.GetMethod("SayHello" ); sayHelloMethod.Invoke(personObj, null ); Console.WriteLine($"Name: {nameProperty.GetValue(personObj)} " ); Console.WriteLine($"Age: {ageProperty.GetValue(personObj)} " ); } }
7. 序列化库 序列化库位于 System.Runtime.Serialization 和 System.Text.Json(.NET Core 3.0+)命名空间。
常用类
类
功能
使用示例
JsonSerializer
JSON 序列化/反序列化
JsonSerializer.Serialize(obj);
XmlSerializer
XML 序列化/反序列化
XmlSerializer serializer = new XmlSerializer(typeof(T));
BinaryFormatter
二进制序列化/反序列化
BinaryFormatter formatter = new BinaryFormatter();
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System;using System.Text.Json;class Person { public string Name { get ; set ; } public int Age { get ; set ; } } class Program { static void Main () { Person person = new Person { Name = "John" , Age = 30 }; string json = JsonSerializer.Serialize(person); Console.WriteLine("Serialized JSON:" ); Console.WriteLine(json); Person deserializedPerson = JsonSerializer.Deserialize<Person>(json); Console.WriteLine("\nDeserialized object:" ); Console.WriteLine($"Name: {deserializedPerson.Name} " ); Console.WriteLine($"Age: {deserializedPerson.Age} " ); } }
8. 正则表达式库 正则表达式库位于 System.Text.RegularExpressions 命名空间。
常用类
类
功能
使用示例
Regex
正则表达式操作
Regex regex = new Regex(@"\d+");
Match
匹配结果
Match match = regex.Match(input);
MatchCollection
多个匹配结果
MatchCollection matches = regex.Matches(input);
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 using System;using System.Text.RegularExpressions;class Program { static void Main () { string input = "Contact: John (555-1234), Jane (555-5678)" ; Regex phoneRegex = new Regex(@"\d{3}-\d{4}" ); MatchCollection matches = phoneRegex.Matches(input); Console.WriteLine("Found phone numbers:" ); foreach (Match match in matches) { Console.WriteLine(match.Value); } string replaced = phoneRegex.Replace(input, "[REDACTED]" ); Console.WriteLine("\nAfter replacement:" ); Console.WriteLine(replaced); string email = "user@example.com" ; Regex emailRegex = new Regex(@"^[\w.-]+@[\w.-]+\.\w+$" ); bool isValid = emailRegex.IsMatch(email); Console.WriteLine($"\nEmail '{email} ' is valid: {isValid} " ); } }
9. LINQ(语言集成查询) LINQ 位于 System.Linq 命名空间,提供统一的查询语法。
常用方法
方法
功能
使用示例
Where
筛选元素
var result = list.Where(x => x > 5);
Select
投影元素
var result = list.Select(x => x * 2);
OrderBy
排序元素
var result = list.OrderBy(x => x);
GroupBy
分组元素
var result = list.GroupBy(x => x % 2);
First
获取第一个元素
var result = list.First();
Last
获取最后一个元素
var result = list.Last();
Count
计算元素数量
int count = list.Count();
Sum
计算元素总和
int sum = list.Sum();
使用示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 using System;using System.Linq;using System.Collections.Generic;class Program { static void Main () { List<int > numbers = new List<int > { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 }; var evenNumbers = numbers.Where(n => n % 2 == 0 ); Console.WriteLine("Even numbers:" ); foreach (var num in evenNumbers) { Console.WriteLine(num); } var squaredNumbers = numbers.Select(n => n * n).OrderBy(n => n); Console.WriteLine("\nSquared numbers (sorted):" ); foreach (var num in squaredNumbers) { Console.WriteLine(num); } int sum = numbers.Sum(); double average = numbers.Average(); int max = numbers.Max(); int min = numbers.Min(); Console.WriteLine($"\nSum: {sum} " ); Console.WriteLine($"Average: {average} " ); Console.WriteLine($"Max: {max} " ); Console.WriteLine($"Min: {min} " ); List<Person> people = new List<Person> { new Person { Name = "John" , Age = 30 }, new Person { Name = "Jane" , Age = 25 }, new Person { Name = "Bob" , Age = 35 } }; var adults = people.Where(p => p.Age >= 30 ).OrderBy(p => p.Name); Console.WriteLine("\nAdults (sorted by name):" ); foreach (var person in adults) { Console.WriteLine($"{person.Name} , {person.Age} " ); } } } class Person { public string Name { get ; set ; } public int Age { get ; set ; } }
C# 标准库与 Java 标准库的对比 1. 整体架构
特性
C# 标准库
Java 标准库
运行环境
.NET Framework / .NET Core / .NET 5+
JVM
版本控制
.NET 版本号(如 .NET 8.0)
Java SE 版本号(如 Java 21)
模块化
.NET Core 开始采用模块化设计
Java 9+ 引入模块系统
跨平台
.NET Core/5+ 支持跨平台
支持跨平台
性能
近年来性能显著提升,部分场景超越 Java
成熟稳定,JIT 优化优秀
2. 核心组件对比 2.1 基础类型
功能
C#
Java
对比
字符串
string / String
String
C# 有 string 别名,更简洁
日期时间
DateTime
LocalDateTime, Date
C# 的 DateTime 更统一
数学运算
Math
Math
功能相似
控制台
Console
System.out
C# 的 Console 功能更丰富
随机数
Random
Random
C# 的 Random 更易用
2.2 集合框架
集合类型
C#
Java
对比
列表
List<T>
ArrayList, LinkedList
C# 的 List<T> 更常用
字典
Dictionary<K, V>
HashMap, TreeMap
功能相似,C# 语法更简洁
集合
HashSet<T>
HashSet, TreeSet
功能相似
队列
Queue<T>
Queue
功能相似
栈
Stack<T>
Stack
功能相似
链表
LinkedList<T>
LinkedList
功能相似
并发集合
ConcurrentDictionary<T>, etc.
ConcurrentHashMap, etc.
功能相似
2.3 IO 操作
功能
C#
Java
对比
文件操作
File, FileInfo
Files, Path
C# 有静态类和实例类两种方式
目录操作
Directory, DirectoryInfo
Files, Paths
功能相似
流操作
StreamReader, StreamWriter
BufferedReader, BufferedWriter
功能相似
二进制操作
BinaryReader, BinaryWriter
DataInputStream, DataOutputStream
功能相似
2.4 网络编程
功能
C#
Java
对比
HTTP 客户端
HttpClient
HttpClient
功能相似,C# 的 HttpClient 更现代
TCP 客户端
TcpClient
Socket
C# 的 TcpClient 更高级
TCP 服务器
TcpListener
ServerSocket
C# 的 TcpListener 更易用
套接字
Socket
Socket
功能相似
2.5 多线程
功能
C#
Java
对比
线程
Thread
Thread
功能相似
异步任务
Task
CompletableFuture
C# 的 async/await 语法更简洁
线程池
ThreadPool
Executors
Java 的 Executors 提供更多工厂方法
锁机制
lock, Monitor, Mutex
synchronized, ReentrantLock
C# 的 lock 语法更简洁
并发工具
Semaphore, AutoResetEvent
Semaphore, CountDownLatch
功能相似
2.6 反射
功能
C#
Java
对比
类型信息
Type
Class
C# 的 Type 更统一
程序集
Assembly
ClassLoader, Module
C# 的 Assembly 概念更清晰
创建实例
Activator.CreateInstance
Class.newInstance, Constructor.newInstance
C# 的方式更简洁
方法调用
MethodInfo.Invoke
Method.invoke
功能相似
2.7 序列化
功能
C#
Java
对比
JSON 序列化
System.Text.Json
Jackson, Gson
C# 内置 JSON 支持,Java 常用第三方库
XML 序列化
XmlSerializer
JAXB
功能相似
二进制序列化
BinaryFormatter
ObjectOutputStream
功能相似
2.8 其他功能
功能
C#
Java
对比
正则表达式
Regex
Pattern, Matcher
C# 的 Regex 使用更简洁
LINQ
System.Linq
流 API (Stream)
C# 的 LINQ 语法更强大,Java 的流 API 更函数式
异步编程
async/await
CompletableFuture, CompletableStage
C# 的 async/await 语法更简洁
扩展方法
支持
不支持(Java 8+ 有默认方法)
C# 的扩展方法更灵活
委托和事件
delegate, event
接口 + 匿名内部类,lambda
C# 的委托和事件语法更简洁
特性(注解)
Attribute
Annotation
功能相似
3. 语法和使用风格对比 3.1 语法风格
C# :更注重语法简洁性和表达力,如 var 类型推断、async/await 异步语法、扩展方法等
Java :更注重代码的清晰性和一致性,语法相对保守但更严谨
3.2 异常处理
C# :区分检查异常和非检查异常,但语法更简洁
Java :强制要求处理检查异常,代码更冗长但更安全
3.3 泛型实现
C# :运行时泛型,保留类型信息
Java :类型擦除,运行时不保留类型信息
3.4 内存管理
C# :垃圾回收器,支持析构函数和 IDisposable 接口
Java :垃圾回收器,支持 finalize() 方法
3.5 跨平台支持
C# :.NET Core/5+ 支持跨平台
Java :原生支持跨平台
最佳实践 1. 选择合适的库
根据应用场景选择合适的库组件
优先使用 .NET Core/5+ 中的现代 API
对于性能敏感的场景,选择更底层的 API
2. 性能优化
使用 async/await 处理 I/O 操作
合理使用缓存减少重复计算
选择合适的集合类型
避免不必要的装箱和拆箱
合理使用并行编程
3. 代码质量
遵循 .NET 设计规范
使用 using 语句管理资源
合理处理异常
编写单元测试
使用代码分析工具
4. 安全性
避免使用不安全的代码
注意输入验证
使用安全的加密算法
遵循最佳安全实践
总结 C# 标准库是一个功能强大、设计优雅的库集合,它为 C# 开发者提供了丰富的工具和功能,涵盖了从基础类型操作到高级网络编程的各个方面。
与 Java 标准库相比,C# 标准库在以下方面具有优势:
语法简洁性 :如 var 类型推断、async/await 异步语法等
统一的 API 设计 :如 DateTime 类的统一设计
强大的 LINQ :提供了更灵活的查询语法
现代的异步编程模型 :async/await 语法更简洁易用
扩展方法 :允许向现有类型添加方法
同时,Java 标准库在以下方面具有优势:
更成熟的生态系统 :第三方库更丰富
更严格的类型系统 :强制检查异常
更统一的集合框架 :设计更一致
更好的跨平台支持 :原生支持跨平台
无论是 C# 还是 Java,它们的标准库都是各自语言的重要组成部分,掌握它们的使用对于提高开发效率和代码质量至关重要。
参考资料