全面的 C# 备忘单旨在帮助开发人员掌握与 C# 编程相关的关键语法和概念。
所有 C# 程序都遵循一个基本结构,概述如下:
using System; public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello, World!"); } }
从 .NET 5 开始,顶级语句简化了 Program.cs 内容:
Console.WriteLine("Hello, World");
C# 支持多种数据类型,例如:
变量是值的符号名称:
int age = 30; // integer variable string name = "John"; // string variable double PI = 3.14159; // double for floating-point numbers bool isLoggedIn = true; // boolean variable
使用 'var' 进行类型推断:
var number = 5; // compiler infers type as int var message = "This is a message"; // compiler infers type as string
常量保存不可变的值:
const double GRAVITY = 9.81; // constant for gravitational acceleration const string COMPANY_NAME = "MyCompany"; // constant company name
根据条件控制程序流程:
int age = 20; if (age >= 18) { Console.WriteLine("You are eligible to vote."); } else { Console.WriteLine("You are not eligible to vote."); } switch (variable) { /*...*/ } // Switch statement
重复执行代码:
for (int i = 1; i <= 5; i++) { Console.WriteLine(i); } foreach (var item in collection) { /*...*/ } // Foreach loop while (condition) { /*...*/ } // While loop do { /*...*/ } while (condition); // Do-while loop
固定大小的元素集合:
string[] names = new string[3] { "Alice", "Bob", "Charlie" }; Console.WriteLine(names[1]); // Output: Bob (accessing element at index 1)
动态集合类似于数组:
List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); foreach (var number in numbers) { Console.WriteLine(number); }
数据关联的键值对:
Dictionary<string, string> phonebook = new Dictionary<string, string>(); phonebook.Add("John Doe", "123-456-7890"); phonebook.Add("Jane Doe", "987-654-3210"); Console.WriteLine(phonebook["John Doe"]); // Output: 123-456-7890
封装可重用逻辑:
public class Rectangle { public double Width { get; set; } public double Height { get; set; } public double GetArea() { return Width * Height; } } public class Program { public static void Main(string[] args) { Rectangle rect = new Rectangle(); rect.Width = 5; rect.Height = 10; double area = rect.GetArea(); Console.WriteLine($"Area of rectangle: {area}"); } }
类定义对象的蓝图:
public class MyClass // Class definition { public string PropertyName { get; set; } // Properties store data public void MethodName() { /*...*/ } // Methods define actions } MyClass obj = new MyClass(); // Object creation
优雅地管理运行时错误:
public static int GetNumberInput() { while (true) { try { Console.WriteLine("Enter a number: "); string input = Console.ReadLine(); return int.Parse(input); } catch (FormatException) { Console.WriteLine("Invalid input. Please enter a number."); } } } public static void Main(string[] args) { int number = GetNumberInput(); Console.WriteLine($"You entered: {number}"); }
对于事件驱动编程和方法处理:
public delegate void MyDelegate(); // Delegate declaration event MyDelegate MyEvent; // Event declaration public class Person { public string Name { get; set; } public int Age { get; set; } } public static void Main(string[] args) { List<Person> people = new List<Person>() { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 40 }, }; people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name)); foreach (var person in people) { Console.WriteLine(person.Name); // Output: Alice, Bob, Charlie (sorted by name) } }
数据操作的查询功能:
using System.Linq; public static void Main(string[] args) { List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6 }; var evenNumbers = numbers.Where(x => x % 2 == 0); foreach (var number in evenNumbers) { Console.WriteLine(number); // Output: 2, 4, 6 } }
将元数据添加到代码元素:
[Obsolete("Use the new DoSomethingV2 method instead.")] public void DoSomething() { // Implementation here } public void DoSomethingV2() { // New and improved implementation }
对于非阻塞代码执行:
using System.Threading.Tasks; public static async Task DownloadFileAsync(string url, string filePath) { // Simulate downloading data asynchronously await Task.Delay(2000); // Simulate a 2-second download // Write downloaded data to the file File.WriteAllText(filePath, "Downloaded content"); Console.WriteLine($"File downloaded to: {filePath}"); } public static void Main(string[] args) { string url = "https://example.com/data.txt"; string filePath = "downloaded_data.txt"; DownloadFileAsync(url, filePath); // Continue program execution while download happens in the background Console.WriteLine("Downloading file..."); Console.WriteLine("Meanwhile, you can do other things..."); }
其他语言功能:
强大的字符串处理方法:
string.Concat(); // Combine strings string.Join(); // Join elements str.Split(); // Split string str.ToUpper(); // Convert to uppercase str.ToLower(); // Convert to lowercase
文件操作:
using System.IO; // Required for File I/O File.ReadAllText(path); // Read file content File.WriteAllText(path, content); // Write to file File.Exists(path); // Check file existence
日期和时间操作:
using System; public static void Main(string[] args) { DateTime startDate = DateTime.Parse("2024-03-10"); DateTime endDate = DateTime.Now; TimeSpan difference = endDate - startDate; Console.WriteLine($"Time difference: {difference.Days} days, {difference.Hours} hours"); }
类型安全的数据结构:
public class Stack<T> { private List<T> items = new List<T>(); public void Push(T item) { items.Add(item); } public T Pop() { T item = items[items.Count - 1]; items.RemoveAt(items.Count - 1); return item; } } public static void Main(string[] args) { Stack<string> messages = new Stack<string>(); messages.Push("Hello"); messages.Push("World"); string message = messages.Pop(); Console.WriteLine(message); // Output: World }
允许值类型为空:
int? nullableInt = null; // Nullable integer
元数据和类型自省:
public class Person { public string Name { get; set; } public int Age { get; set; } } public static void Main(string[] args) { Type personType = typeof(Person); PropertyInfo[] properties = personType.GetProperties(); foreach (PropertyInfo property in properties) { Console.WriteLine(property.Name); // Output: Name, Age } }
向现有类型添加方法:
public static class StringExtensions { public static string ToUppercase(this string str) { return str.ToUpper(); } } public static void Main(string[] args) { string message = "Hello, world!"; string uppercased = message.ToUppercase(); // Using the extension method Console.WriteLine(uppercased); // Output: HELLO, WORLD! }
松耦合的代码设计:
public interface ILogger { void LogMessage(string message); } public class MyService { private readonly ILogger _logger; public MyService(ILogger logger) { _logger = logger; } public void DoSomething() { _logger.LogMessage("Doing something..."); } } // Implementing the ILogger interface (example) public class ConsoleLogger : ILogger { public void LogMessage(string message) { Console.WriteLine(message); } } public static void Main(string[] args) { ILogger logger = new ConsoleLogger(); MyService service = new MyService(logger); service.DoSomething(); }
拆分单个类定义:
public partial class MyClass { /*...*/ } // Partial class definition
与其他语言的互操作:
using System; using System.Runtime.InteropServices; [DllImport("user32.dll")] public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType); public static void Main(string[] args) { MessageBox(IntPtr.Zero, "Hello from C#!", "Interop Example", 0); }
创建未命名类型:csharp复制代码
var person = new { Name = "John", Age = 30 }; Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
具有特定数量元素的数据结构:
(string Name, int Age) person = ("Alice", 30); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Accessing elements using Item1 and Item2
简化某些编程任务:
object obj = new Person { Name = "Bob", Age = 25 }; if (obj is Person { Name: "Bob", Age >= 18 }) { Console.WriteLine("Bob is an adult."); }
将逻辑封装在方法中:
public static int Calculate(int number) { int Factorial(int n) { if (n == 0) return 1; return n * Factorial(n - 1); } return Factorial(number); } public static void Main(string[] args) { int result = Calculate(5); Console.WriteLine($"5! = {result}"); }
引用类型的简洁语法:
public record Person(string Name, int Age); public static void Main(string[] args) { Person person1 = new Person("Alice", 30); Person person2 = new Person("Alice", 30); // Records provide default equality comparison if (person1 == person2) { Console.WriteLine("People are equal"); } }
记录的非破坏性突变:
var john = new Person("John", 30); var jane = john with { Name = "Jane" }; // Non-destructive mutation
灵活的数据访问:
int[] arr = {0, 1, 2, 3, 4, 5}; var subset = arr[1..^1]; // Indexer and range usage
处置 IDisposable 对象:
using var reader = new StreamReader("file.txt"); // using declaration
避免空引用异常:
public class Person { public string Name { get; set; } public int Age { get; set; } } public static void Main(string[] args) { Person person = new Person() { Age = 30 }; // NRTs require null checks before accessing properties if (person?.Name != null) { Console.WriteLine(person.Name); } else { Console.WriteLine("Name is null"); } }
using 语句中的更多模式:
public ref struct ResourceWrapper { /*...*/ } // Resource wrapper using var resource = new ResourceWrapper(); // Pattern-based using
解构模式匹配中的对象:
if (obj is Person { Name: "John", Age: var age }) { /*...*/ } // Property pattern matching
具有默认方法实现的接口:
public interface IPerson { /*...*/ } // Interface with default method public class MyClass : IPerson { /*...*/ } // Class implementing interface
运行时类型解析:
dynamic d = 5; // Dynamic binding d = "Hello"; // No compile-time type checking
这份结构化的 C# 备忘单以高级主题和技术作为结尾,为旨在提高 C# 编程技能的开发人员提供了全面的参考。有关详细示例和进一步探索,请参阅本指南中概述的具体部分。快乐编码!
感谢您成为 C# 社区的一员!离开之前:
访问我们的其他平台: GitHub | Instagram |抖音|知乎|每日开发版
灵感来源: https ://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants
也发布在这里