C# 是一种现代、通用的编程语言,它由微软在2000年发布,作为.NET框架的一部分。C# 是一种面向对象的语言,结合了C++的高性能和Visual Basic的易用性。本文将详细介绍C#的基础语法,从数据类型、变量、运算符到控制结构、方法、类和对象等,并涵盖注释方式、命名规则、异常处理等重要内容,帮助读者全面掌握C#的基础知识。
引言
C# 作为一种现代编程语言,以其简洁、强大和高效的特性,成为许多开发者的首选语言之一。它不仅适用于桌面应用开发,还广泛用于Web应用、游戏开发、移动应用等领域。本篇文章将通过详细的讲解和丰富的代码示例,带领读者深入理解C#的基础语法和编程技巧。
数据类型和变量
C# 提供了丰富的数据类型,以满足不同的编程需求。这些数据类型主要分为两类:值类型和值类型。
值类型
值类型直接存储数据,存储在栈中。C# 的基本值类型包括:
int: 代表整数类型,如int age = 25;float: 代表单精度浮点数,如float temperature = 36.6f;double: 代表双精度浮点数,如double pi = 3.14159;char: 代表单个字符,如char grade = 'A';bool: 代表布尔值,如bool isStudent = true;
引用类型
引用类型存储的是对象的引用,存储在堆中。常见的引用类型包括:
string: 代表字符串,如string name = "Alice";object: 所有类型的基类,如object obj = 42;- 类(class)
- 接口(interface)
- 数组(array)
变量声明和初始化
在C#中,变量声明时必须指定类型,且可以在声明的同时进行初始化:
int number = 10;float price = 19.99f;string message = "Hello, World!";
注释
注释是程序员用来解释代码的文本,不会被编译器执行。C# 支持单行注释和多行注释两种方式。
单行注释
使用 // 符号表示单行注释:
// 这是一个单行注释int number = 42; // 声明一个整型变量
多行注释
使用 /* */ 符号表示多行注释:
/* 这是一个多行注释它可以跨越多行 */int number = 42; /* 声明一个整型变量 */
运算符
运算符是用于执行各种操作的符号。C# 中的运算符分为以下几类:
算术运算符
用于执行基本的数学运算:
+: 加法,如int sum = a + b;-: 减法,如int difference = a - b;*: 乘法,如int product = a * b;/: 除法,如int quotient = a / b;%: 取余,如int remainder = a % b;
关系运算符
用于比较两个值之间的关系:
==: 等于,如if (a == b) { }!=: 不等于,如if (a != b) { }>: 大于,如if (a > b) { }<: 小于,如if (a < b) { }>=: 大于或等于,如if (a >= b) { }<=: 小于或等于,如if (a <= b) { }
逻辑运算符
用于执行逻辑操作:
&&: 逻辑与,如if (a > 0 && b > 0) { }||: 逻辑或,如if (a > 0 || b > 0) { }!: 逻辑非,如if (!flag) { }
赋值运算符
用于给变量赋值:
=: 赋值,如int a = 10;+=: 加法赋值,如a += 5;等价于a = a + 5;-=: 减法赋值,如a -= 5;等价于a = a - 5;*=: 乘法赋值,如a *= 5;等价于a = a * 5;/=: 除法赋值,如a /= 5;等价于a = a / 5;%=: 取余赋值,如a %= 5;等价于a = a % 5;
位运算符
用于对二进制位进行操作:
&: 按位与,如a & b|: 按位或,如a | b^: 按位异或,如a ^ b~: 按位取反,如~a<<: 左移,如a << 2>>: 右移,如a >> 2
控制结构
控制结构用于控制程序的执行流程,包括条件语句和循环语句。
条件语句
条件语句根据表达式的真假来决定执行的代码块。
if 语句
根据条件表达式的值来执行相应的代码块:
int number = 10;if (number > 0){Console.WriteLine("Positive number");}else if (number < 0){Console.WriteLine("Negative number");}else{Console.WriteLine("Zero");}
switch 语句
用于在多个可能的选项中选择一个执行:
int day = 3;switch (day){case 1:Console.WriteLine("Monday");break;case 2:Console.WriteLine("Tuesday");break;case 3:Console.WriteLine("Wednesday");break;default:Console.WriteLine("Invalid day");break;}
循环语句
循环语句用于重复执行一段代码。
for 循环
用于执行已知次数的循环:
for (int i = 0; i < 10; i++){Console.WriteLine(i);}
while 循环
用于执行未知次数的循环,直到条件表达式为假:
int i = 0;while (i < 10){Console.WriteLine(i);i++;}
do-while 循环
至少执行一次循环,然后根据条件表达式决定是否继续执行:
int i = 0;do{Console.WriteLine(i);i++;} while (i < 10);
foreach 循环
用于遍历集合中的元素:
int[] numbers = { 1, 2, 3, 4, 5 };foreach (int number in numbers){Console.WriteLine(number);}
方法
方法是执行特定任务的代码块。C# 的方法具有返回类型、名称、参数列表和主体。
方法声明
一个简单的方法示例如下:
public int Add(int a, int b){return a + b;}
调用方法:
int result = Add(5, 10);Console.WriteLine(result); // 输出15
方法重载
方法重载是指在同一个类中可以定义多个具有相同名称但参数不同的方法:
public int Add(int a, int b){return a + b;}public double Add(double a, double b){return a + b;}
调用方法:
int result1 = Add(5, 10); // 调用第一个Add方法double result2 = Add(5.5, 10.5); // 调用第二个Add方法
可选参数
C# 支持为方法定义可选参数,如果调用方法时没有提供这些参数,则使用默认值:
public void PrintMessage(string message = "Hello, World!"){Console.WriteLine(message);}PrintMessage(); // 输出 "Hello, World!"PrintMessage("Hi there!"); // 输出 "Hi there!"
类和对象
C# 是一种面向对象的编程语言,类和对象是其核心概念。
类的定义
类是对象的蓝图,定义了对象的属性和行为:
public class Person{// 属性public string Name { get; set; }public int Age { get; set; }// 构造函数public Person(string name, int age){Name = name;Age = age;}// 方法public void Introduce(){Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");}}
创建对象
对象是类的实例,通过 new 关键字创建:
Person person = new Person("Alice", 30);person.Introduce(); // 输出 "Hi, I'm Alice and I'm 30 years old."
继承
继承是面向对象编程的重要特性,允许一个类从另一个类继承属性和方法:
public class Employee : Person{public string Company { get; set; }public Employee(string name, int age, string company): base(name, age){Company = company;}public void Work(){Console.WriteLine($"{Name} is working at {Company}.");}}Employee employee = new Employee("Bob", 35, "ACME Corp");employee.Introduce(); // 输出 "Hi, I'm Bob and I'm 35 years old."employee.Work(); // 输出 "Bob is working at ACME Corp."
多态
多态允许使用基类的引用来调用子类的方法:
public class Animal{public virtual void Speak(){Console.WriteLine("Animal speaks.");}}public class Dog : Animal{public override void Speak(){Console.WriteLine("Dog barks.");}}public class Cat : Animal{public override void Speak(){Console.WriteLine("Cat meows.");}}Animal myDog = new Dog();Animal myCat = new Cat();myDog.Speak(); // 输出 "Dog barks."myCat.Speak(); // 输出 "Cat meows."
命名规则
良好的命名规则可以提高代码的可读性和可维护性。C# 通常遵循以下命名规则:
- 类名和接口名使用 Pascal 大小写,例如
Person、IShape。 - 方法名、属性名和事件名使用 Pascal 大小写,例如
GetName、CalculateArea。 - 变量名和参数名使用 camel 大小写,例如
firstName、totalAmount。 - 常量名使用全大写字母和下划线,例如
MAX_VALUE。
数组
数组是一种用于存储相同类型数据的集合。
一维数组
声明和初始化一维数组:
int[] numbers = new int[5];numbers[0] = 1;numbers[1] = 2;// 或者int[] numbers = { 1, 2, 3, 4, 5 };
遍历数组:
foreach (int number in numbers){Console.WriteLine(number);}
多维数组
声明和初始化多维数组:
int[,] matrix = new int[2, 3];matrix[0, 0] = 1;matrix[0, 1] = 2;matrix[0, 2] = 3;// 或者int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };
遍历多维数组:
for (int i = 0; i < matrix.GetLength(0); i++){for (int j = 0; j < matrix.GetLength(1); j++){Console.WriteLine(matrix[i, j]);}}
交错数组
声明和初始化交错数组:
int[][] jaggedArray = new int[2][];jaggedArray[0] = new int[] { 1, 2, 3 };jaggedArray[1] = new int[] { 4, 5 };foreach (int[] array in jaggedArray){foreach (int number in array){Console.WriteLine(number);}}
字符串
字符串是字符的集合,在C#中是引用类型。
字符串操作
字符串的常见操作包括连接、比较、查找、替换等。
字符串连接
使用 + 运算符或 String.Concat 方法连接字符串:
string firstName = "John";string lastName = "Doe";string fullName = firstName + " " + lastName;// 或者string fullName = String.Concat(firstName, " ", lastName);
字符串插值
使用 $ 字符和花括号 {} 进行字符串插值:
string name = "Alice";int age = 25;string message = $"Hi, I'm {name} and I'm {age} years old.";
字符串比较
使用 == 运算符或 String.Compare 方法比较字符串:
string str1 = "Hello";string str2 = "hello";bool areEqual = str1 == str2; // falseint comparison = String.Compare(str1, str2, true); // 0 (忽略大小写)
字符串查找
使用 String.IndexOf 方法查找子字符串的位置:
string message = "Hello, world!";int index = message.IndexOf("world"); // 7
字符串替换
使用 String.Replace 方法替换子字符串:
string message = "Hello, world!";string newMessage = message.Replace("world", "C#"); // "Hello, C#!"
字符串常用方法
C# 提供了丰富的字符串处理方法,例如 Substring、Split、Trim 等。
Substring
从字符串中提取子字符串:
string message = "Hello, world!";string hello = message.Substring(0, 5); // "Hello"
Split
根据指定的分隔符拆分字符串:
string message = "apple,banana,cherry";string[] fruits = message.Split(','); // {"apple", "banana", "cherry"}
Trim
移除字符串开头和结尾的空白字符:
string message = " Hello, world! ";string trimmedMessage = message.Trim(); // "Hello, world!"
集合
集合用于存储和管理一组相关的对象。C# 提供了多种集合类型,如列表、字典、队列和栈。
List
List<T> 是一种动态数组,可以存储任意类型的对象,并提供了丰富的方法来操作这些对象。
创建和初始化列表
创建和初始化一个列表:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
添加元素
使用 Add 方法向列表添加元素:
numbers.Add(6);
访问元素
使用索引访问列表中的元素:
int firstNumber = numbers[0]; // 1
遍历列表
使用 foreach 循环遍历列表中的元素:
foreach (int number in numbers){Console.WriteLine(number);}
Dictionary
Dictionary<TKey, TValue> 是一种键值对集合,用于存储具有唯一键的对象。
创建和初始化字典
创建和初始化一个字典:
Dictionary<string, int> ages = new Dictionary<string, int>{{ "Alice", 25 },{ "Bob", 30 }};
添加元素
使用 Add 方法向字典添加键值对:
ages.Add("Charlie", 35);
访问元素
使用键访问字典中的值:
int aliceAge = ages["Alice"]; // 25
遍历字典
使用 foreach 循环遍历字典中的键值对:
foreach (KeyValuePair<string, int> entry in ages){Console.WriteLine($"{entry.Key}: {entry.Value}");}
Queue
Queue<T> 是一种先进先出(FIFO)的集合,用于按顺序存储元素。
创建和初始化队列
创建和初始化一个队列:
Queue<string> queue = new Queue<string>();
添加元素
使用 Enqueue 方法向队列添加元素:
queue.Enqueue("Alice");queue.Enqueue("Bob");
移除和访问元素
使用 Dequeue 方法移除并返回队列中的第一个元素:
string first = queue.Dequeue(); // "Alice"
访问队列头部元素
使用 Peek 方法访问但不移除队列中的第一个元素:
string next = queue.Peek(); // "Bob"
Stack
Stack<T> 是一种后进先出(LIFO)的集合,用于按顺序存储元素。
创建和初始化
栈 创建和初始化一个栈:
Stack<string> stack = new Stack<string>();
添加元素
使用 Push 方法向栈添加元素:
stack.Push("Alice");stack.Push("Bob");
移除和访问元素
使用 Pop 方法移除并返回栈顶元素:
string top = stack.Pop(); // "Bob"
访问栈顶元素
使用 Peek 方法访问但不移除栈顶元素:
string next = stack.Peek(); // "Alice"
异常处理
异常处理是指在程序运行过程中捕获和处理异常,以防止程序崩溃并提供有意义的错误信息。
try-catch 语句
使用 try-catch 语句捕获和处理异常:
try{int result = 10 / 0;}catch (DivideByZeroException ex){Console.WriteLine("Cannot divide by zero.");}catch (Exception ex){Console.WriteLine("An error occurred: " + ex.Message);}
finally 语句
finally 语句用于执行无论是否发生异常都要执行的代码:
try{int result = 10 / 0;}catch (DivideByZeroException ex){Console.WriteLine("Cannot divide by zero.");}finally{Console.WriteLine("Execution completed.");}
抛出异常
使用 throw 关键字显式抛出异常:
public void Divide(int a, int b){if (b == 0){throw new DivideByZeroException("Divisor cannot be zero.");}Console.WriteLine(a / b);}try{Divide(10, 0);}catch (DivideByZeroException ex){Console.WriteLine(ex.Message);}
文件操作
C# 提供了丰富的文件操作类,用于读取和写入文件。
读取文件
使用 StreamReader 读取文件内容:
using System.IO;string path = "example.txt";using (StreamReader reader = new StreamReader(path)){string content = reader.ReadToEnd();Console.WriteLine(content);}
写入文件
使用 StreamWriter 写入文件内容:
using System.IO;string path = "example.txt";string content = "Hello, world!";using (StreamWriter writer = new StreamWriter(path)){writer.WriteLine(content);}
文件存在性检查
使用 File.Exists 方法检查文件是否存在:
string path = "example.txt";if (File.Exists(path)){Console.WriteLine("File exists.");}else{Console.WriteLine("File does not exist.");}
异步编程
异步编程是一种编程模式,允许程序在等待某些操作完成时不阻塞主线程。
async 和 await 关键字
使用 async 和 await 关键字编写异步方法:
using System.Net.Http;using System.Threading.Tasks;public async Task<string> FetchDataAsync(string url){using (HttpClient client = new HttpClient()){string result = await client.GetStringAsync(url);return result;}}async Task Main(){string data = await FetchDataAsync("http://example.com");Console.WriteLine(data);}
Task 类
使用 Task 类表示异步操作:
public async Task<int> ComputeAsync(int a, int b){return await Task.Run(() =>{// 模拟长时间计算System.Threading.Thread.Sleep(2000);return a + b;});}async Task Main(){int result = await ComputeAsync(5, 10);Console.WriteLine(result); // 输出15}
事件
事件是一种用于在对象之间传递消息的机制,常用于实现事件驱动编程。
定义事件
使用 event 关键字定义事件:
public class Alarm{public event EventHandler Ring;public void Trigger(){if (Ring != null){Ring(this, EventArgs.Empty);}}}
订阅和触发事件
使用 += 运算符订阅事件,使用 -= 运算符取消订阅:
public class Program{static void Main(){Alarm alarm = new Alarm();alarm.Ring += Alarm_Ring;alarm.Trigger();}private static void Alarm_Ring(object sender, EventArgs e){Console.WriteLine("Alarm triggered!");}}
委托
委托是C#中的一种类型安全的函数指针,允许你将方法作为参数传递。
定义委托
使用 delegate 关键字定义委托:
public delegate void Notify(string message);
使用委托
创建委托实例并调用方法:
public class Program{public static void Main(){Notify notify = new Notify(ShowMessage);notify("Hello, delegates!");}public static void ShowMessage(string message){Console.WriteLine(message);}}
多播委托
多播委托可以指向多个方法,并依次调用这些方法:
public delegate void Notify(string message);public class Program{public static void Main(){Notify notify = ShowMessage;notify += ShowAnotherMessage;notify("Hello, delegates!");}public static void ShowMessage(string message){Console.WriteLine("Message: " + message);}public static void ShowAnotherMessage(string message){Console.WriteLine("Another message: " + message);}}
Lambda 表达式
Lambda 表达式是一种简洁的匿名函数语法,常用于简化委托和 LINQ 表达式。
定义 Lambda 表达式
使用 => 运算符定义 Lambda 表达式:
Func<int, int, int> add = (a, b) => a + b;int result = add(5, 10); // 输出15
Lambda 表达式与 LINQ
结合 Lambda 表达式和 LINQ 查询数据:
int[] numbers = { 1, 2, 3, 4, 5 };var evenNumbers = numbers.Where(n => n % 2 == 0);foreach (int number in evenNumbers){Console.WriteLine(number); // 输出2 4}
LINQ
语言集成查询(LINQ)是一种查询数据的功能,允许你使用类似SQL的语法来查询集合。
LINQ 查询语法
使用 LINQ 查询语法查询数据:
int[] numbers = { 1, 2, 3, 4, 5 };var evenNumbers = from number in numberswhere number % 2 == 0select number;foreach (int number in evenNumbers){Console.WriteLine(number); // 输出2 4}
LINQ 方法语法
使用 LINQ 方法语法查询数据:
int[] numbers = { 1, 2, 3, 4, 5 };var evenNumbers = numbers.Where(n => n % 2 == 0).Select(n => n);foreach (int number in evenNumbers){Console.WriteLine(number); // 输出2 4}
属性
属性是类中的变量,通过访问器(getter 和 setter)来控制对这些变量的访问。
自动属性
使用自动属性简化属性定义:
public class Person{public string Name { get; set; }public int Age { get; set; }}
手动属性
使用手动属性定义带有访问器的属性:
public class Person{private int age;public int Age{get { return age; }set{if (value >= 0){age = value;}}}}
索引器
索引器允许类像数组一样通过索引访问其内部数据。
定义索引器
使用 this 关键字定义索引器:
public class DataCollection{private int[] data = new int[10];public int this[int index]{get { return data[index]; }set { data[index] = value; }}}
使用索引器
创建对象并通过索引器访问数据:
DataCollection collection = new DataCollection();collection[0] = 42;int value = collection[0]; // 42
接口
接口定义了一组方法和属性的规范,而不提供实现。
定义接口
使用 interface 关键字定义接口:
public interface IMovable{void Move();}
实现接口
使用 : 符号实现接口:
public class Car :IMovable{public void Move(){Console.WriteLine("Car is moving.");}}
接口多重继承
一个类可以实现多个接口:
public interface IFlyable{void Fly();}public class FlyingCar : IMovable, IFlyable{public void Move(){Console.WriteLine("FlyingCar is moving.");}public void Fly(){Console.WriteLine("FlyingCar is flying.");}}
抽象类
抽象类是不能被实例化的类,通常用于作为其他类的基类。
定义抽象类
使用 abstract 关键字定义抽象类和抽象方法:
public abstract class Animal{public abstract void Speak();}
继承抽象类
使用 override 关键字重写抽象方法:
public class Dog : Animal{public override void Speak(){Console.WriteLine("Dog barks.");}}public class Cat : Animal{public override void Speak(){Console.WriteLine("Cat meows.");}}
枚举
枚举是定义一组命名常量的类型,通常用于表示一组相关的值。
定义枚举
使用 enum 关键字定义枚举:
public enum DaysOfWeek{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}
使用枚举
创建枚举变量并赋值:
DaysOfWeek today = DaysOfWeek.Monday;if (today == DaysOfWeek.Monday){Console.WriteLine("Today is Monday.");}
嵌套类
嵌套类是定义在另一个类内部的类,用于组织相关的类。
定义嵌套类
在外部类内部定义嵌套类:
public class OuterClass{public class NestedClass{public void Display(){Console.WriteLine("This is a nested class.");}}}
使用嵌套类
创建嵌套类的实例并调用其方法:
OuterClass.NestedClass nested = new OuterClass.NestedClass();nested.Display(); // 输出 "This is a nested class."
泛型
泛型允许定义类、接口和方法时使用类型参数,从而使代码更加通用和类型安全。
泛型类
定义泛型类:
public class GenericList<T>{private T[] items = new T[100];private int count = 0;public void Add(T item){items[count++] = item;}public T Get(int index){return items[index];}}
泛型方法
定义泛型方法:
public class Utilities{public T Max<T>(T a, T b) where T : IComparable<T>{return a.CompareTo(b) > 0 ? a : b;}}Utilities utilities = new Utilities();int maxInt = utilities.Max(10, 20); // 20string maxString = utilities.Max("apple", "banana"); // "banana"
扩展方法
扩展方法允许向现有类型添加新的方法,而无需修改类型本身。
定义扩展方法
使用 this 关键字定义扩展方法:
public static class StringExtensions{public static int WordCount(this string str){return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;}}string text = "Hello, world!";int count = text.WordCount(); // 2
动态类型
动态类型允许在运行时确定类型,而不是在编译时确定。
使用 dynamic 关键字
使用 dynamic 关键字声明动态类型:
dynamic obj = 1;Console.WriteLine(obj); // 输出1obj = "Hello, world!";Console.WriteLine(obj); // 输出 "Hello, world!"obj = new { Name = "Alice", Age = 25 };Console.WriteLine(obj.Name); // 输出 "Alice"
匿名类型
匿名类型是一种用于封装一组只读属性的轻量级数据结构。
创建匿名类型
使用 new 关键字创建匿名类型:
var person = new { Name = "Alice", Age = 25 };Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // 输出 "Name: Alice, Age: 25"
异常处理机制
C# 提供了强大的异常处理机制,帮助开发者捕获和处理运行时异常。
自定义异常
创建自定义异常类:
public class CustomException : Exception{public CustomException(string message) : base(message) { }}public class Program{public static void Main(){try{throw new CustomException("This is a custom exception.");}catch (CustomException ex){Console.WriteLine(ex.Message);}}}
文件和流
C# 提供了丰富的文件和流操作类,用于处理文件输入输出操作。
文件读写
使用 File 类进行文件读写操作:
string path = "example.txt";string content = "Hello, world!";// 写入文件File.WriteAllText(path, content);// 读取文件string readContent = File.ReadAllText(path);Console.WriteLine(readContent); // 输出 "Hello, world!"
使用 FileStream
使用 FileStream 进行文件读写操作:
string path = "example.bin";// 写入文件using (FileStream fs = new FileStream(path, FileMode.Create)){byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };fs.Write(data, 0, data.Length);}// 读取文件using (FileStream fs = new FileStream(path, FileMode.Open)){byte[] data = new byte[10];fs.Read(data, 0, data.Length);foreach (byte b in data){Console.Write(b + " "); // 输出 "0 1 2 3 4 5 6 7 8 9"}}
JSON 处理
C# 提供了丰富的库用于处理 JSON 数据,例如 Json.NET(又名 Newtonsoft.Json)库。
序列化和反序列化
使用 Json.NET 库进行 JSON 序列化和反序列化:
using Newtonsoft.Json;public class Person{public string Name { get; set; }public int Age { get; set; }}Person person = new Person { Name = "Alice", Age = 25 };// 序列化string json = JsonConvert.SerializeObject(person);Console.WriteLine(json); // 输出 {"Name":"Alice","Age":25}// 反序列化Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}"); // 输出 "Name: Alice, Age: 25"
正则表达式
正则表达式是一种用于模式匹配和文本处理的强大工具。
使用正则表达式
使用 Regex 类进行正则表达式操作:
using System.Text.RegularExpressions;string pattern = @"\d+";string input = "There are 123 apples";// 匹配模式Match match = Regex.Match(input, pattern);if (match.Success){Console.WriteLine($"Found match: {match.Value}"); // 输出 "Found match: 123"}// 替换模式string replaced = Regex.Replace(input, pattern, "456");Console.WriteLine(replaced); // 输出 "There are 456 apples"
日期和时间
C# 提供了丰富的日期和时间处理类,如 DateTime、TimeSpan 和 DateTimeOffset。
日期和时间操作
使用 DateTime 类进行日期和时间操作:
DateTime now = DateTime.Now;Console.WriteLine($"Current date and time: {now}");DateTime future = now.AddDays(10);Console.WriteLine($"Future date and time: {future}");TimeSpan duration = future - now;Console.WriteLine($"Duration: {duration.TotalDays} days"); // 输出 "Duration: 10 days"
时间间隔
使用 TimeSpan 类表示时间间隔:
TimeSpan timeSpan = new TimeSpan(1, 2, 30, 45); // 1 day, 2 hours, 30 minutes, 45 secondsConsole.WriteLine($"Total hours: {timeSpan.TotalHours}"); // 输出 "Total hours: 26.5125"
反射
反射是一种在运行时获取类型信息和调用方法的机制。
使用反射获取类型信息
使用 System.Reflection 命名空间
进行反射操作:
using System;using System.Reflection;public class Person{public string Name { get; set; }public int Age { get; set; }public void Introduce(){Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");}}Type type = typeof(Person);Console.WriteLine($"Type: {type.Name}");PropertyInfo[] properties = type.GetProperties();foreach (PropertyInfo property in properties){Console.WriteLine($"Property: {property.Name}");}MethodInfo method = type.GetMethod("Introduce");Console.WriteLine($"Method: {method.Name}");
动态调用方法
使用反射动态调用方法:
Person person = new Person { Name = "Alice", Age = 25 };MethodInfo method = typeof(Person).GetMethod("Introduce");method.Invoke(person, null); // 输出 "Hi, I'm Alice and I'm 25 years old."
异步流
异步流是一种处理异步数据流的方法,通常用于处理大量数据或需要长时间运行的操作。
定义异步流方法
使用 IAsyncEnumerable<T> 定义异步流方法:
using System.Collections.Generic;using System.Threading.Tasks;public class DataGenerator{public async IAsyncEnumerable<int> GetNumbersAsync(){for (int i = 0; i < 10; i++){await Task.Delay(500); // 模拟异步操作yield return i;}}}
消费异步流
使用 await foreach 消费异步流:
DataGenerator generator = new DataGenerator();await foreach (int number in generator.GetNumbersAsync()){Console.WriteLine(number); // 输出 0 1 2 3 4 5 6 7 8 9}
预处理指令
预处理指令用于在编译过程中对代码进行条件编译或定义符号。
常见预处理指令
使用 #define、#if、#else、#elif 和 #endif 预处理指令:
#define DEBUGusing System;public class Program{public static void Main(){#if DEBUGConsole.WriteLine("Debug mode");#elseConsole.WriteLine("Release mode");#endif}}
调试和日志
调试和日志记录是确保代码质量和诊断问题的重要手段。
使用 Debug 类
使用 System.Diagnostics.Debug 类记录调试信息:
using System.Diagnostics;public class Program{public static void Main(){Debug.WriteLine("This is a debug message.");}}
使用日志库
使用 Microsoft.Extensions.Logging 库记录日志:
using Microsoft.Extensions.Logging;using System;public class Program{public static void Main(){using var loggerFactory = LoggerFactory.Create(builder =>{builder.AddConsole();});ILogger logger = loggerFactory.CreateLogger<Program>();logger.LogInformation("This is an info message.");logger.LogWarning("This is a warning message.");logger.LogError("This is an error message.");}}
单元测试
单元测试是验证代码正确性的重要手段。C# 常用的单元测试框架包括 MSTest、NUnit 和 xUnit。
使用 xUnit 进行单元测试
安装 xUnit 包并编写测试代码:
using Xunit;public class Calculator{public int Add(int a, int b){return a + b;}}public class CalculatorTests{[Fact]public void Add_ReturnsSum(){Calculator calculator = new Calculator();int result = calculator.Add(5, 10);Assert.Equal(15, result);}}
结论
C# 是一种功能强大、灵活且易于学习的编程语言,广泛应用于各种领域。通过本文的详细介绍,希望读者对C#的基础语法有了全面的了解,并能在实际开发中充分利用C#的强大功能。无论是初学者还是有经验的开发者,都可以通过不断学习和实践,提升自己的编程技能,成为C#领域的专家。
