C#编程常用代码段集合

需积分: 10 0 下载量 45 浏览量 更新于2024-10-23 收藏 715B ZIP 举报
" C#(发音为“看-尖”)是微软开发的一种面向对象的编程语言,它是.NET框架的一部分。由于其简洁性和强大的功能,C#已成为构建Windows应用程序、Web应用程序、Web服务和游戏等的流行选择。在本文档中,我们将详细介绍一些常用的C#代码段,以帮助开发者提高编码效率和解决编程中的常见问题。 1. 数据类型和变量声明 C#是一种静态类型语言,这意味着在编译时类型必须已知。以下是一些基本的数据类型和变量声明示例: ```csharp int myInt = 10; // 整数 double myDouble = 3.14; // 浮点数 bool myBool = true; // 布尔值 string myString = "Hello World"; // 字符串 char myChar = 'A'; // 字符 ``` 2. 条件语句 条件语句允许根据不同的情况执行不同的代码块。C#中的主要条件语句包括if、else if、else以及switch-case语句。 ```csharp int number = 5; if (number < 0) { Console.WriteLine("Number is negative"); } else if (number == 0) { Console.WriteLine("Number is zero"); } else { Console.WriteLine("Number is positive"); } switch (number) { case 1: Console.WriteLine("Number is one"); break; case 2: Console.WriteLine("Number is two"); break; default: Console.WriteLine("Number is not one or two"); break; } ``` 3. 循环 循环用于重复执行代码块直到满足特定条件。C#中常见的循环类型包括for、foreach、while和do-while。 ```csharp for (int i = 0; i < 5; i++) { Console.WriteLine("The number is: " + i); } int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int number in numbers) { Console.WriteLine(number); } int count = 0; while (count < 5) { Console.WriteLine("Count is: " + count); count++; } do { Console.WriteLine("Count is: " + count); count++; } while (count < 5); ``` 4. 方法定义 在C#中,方法是一段包含一系列语句的代码块,用于执行特定的任务。方法可以具有参数,并可返回值。 ```csharp public int Add(int x, int y) { return x + y; } public void PrintHello() { Console.WriteLine("Hello World!"); } ``` 5. 异常处理 异常处理用于处理程序运行时出现的错误情况。C#使用try-catch块来捕获和处理异常。 ```csharp try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine("Cannot divide by zero!"); } finally { Console.WriteLine("This always executes."); } ``` 6. 类和对象 类是创建对象的蓝图或模板。对象是类的实例,可以包含数据和方法。 ```csharp public class Car { public string Make { get; set; } public string Model { get; set; } public void Drive() { Console.WriteLine("Driving the car"); } } Car myCar = new Car(); myCar.Make = "Toyota"; myCar.Model = "Corolla"; myCar.Drive(); ``` 7. 集合 集合用于存储和操作一组数据元素。C#提供了一些内置的集合类,如List、Dictionary、Queue和Stack等。 ```csharp List<string> myList = new List<string>(); myList.Add("Item 1"); myList.Add("Item 2"); myList.Add("Item 3"); Dictionary<string, int> myDictionary = new Dictionary<string, int>(); myDictionary.Add("One", 1); myDictionary.Add("Two", 2); Queue<int> myQueue = new Queue<int>(); myQueue.Enqueue(1); myQueue.Enqueue(2); Stack<int> myStack = new Stack<int>(); myStack.Push(1); myStack.Push(2); ``` 8. LINQ查询 语言集成查询(LINQ)是C#中用于查询和操作数据的一种强大技术。 ```csharp using System; using System.Linq; List<string> names = new List<string>() { "Alice", "Bob", "Charlie" }; var query = from name in names where name.StartsWith("A") select name; foreach (var name in query) { Console.WriteLine(name); } ``` 9. 异步编程 异步编程允许程序在等待一个长时间运行的操作(如文件操作或网络请求)完成时继续执行其他操作。async和await关键字是C#中处理异步编程的核心。 ```csharp public async Task ProcessFileAsync(string path) { string content = await File.ReadAllTextAsync(path); Console.WriteLine(content); } await ProcessFileAsync("example.txt"); ``` 10. 命名空间 命名空间用于组织代码,防止类名和其他标识符发生冲突。 ```csharp namespace MyNamespace { public class MyClass { // ... } } ``` 11. 属性和字段 属性是一种特殊类型的类成员,用于封装对字段的访问和赋值。字段存储对象的数据。 ```csharp public class Person { private string name; public string Name { get { return name; } set { name = value; } } } ``` 通过学习和理解这些常用的C#代码段,开发者能够更高效地编写代码,并在遇到问题时快速定位解决方案。这些代码段是开发过程中不可或缺的工具,涵盖了C#编程语言的核心概念和结构。