Bảng Cheat C# toàn diện được thiết kế để hỗ trợ các nhà phát triển nắm vững cú pháp và khái niệm chính liên quan đến lập trình C#.
Nội dung
- Cấu trúc cơ bản
- Loại dữ liệu
- Biến
- Hằng số
- Câu điều kiện
- Vòng lặp
- Mảng
- Danh sách
- Từ điển
- phương pháp
- Lớp & Đối tượng
- Xử lý ngoại lệ
- Đại biểu, Sự kiện & Lambdas
- LINQ (Truy vấn tích hợp ngôn ngữ)
- Thuộc tính
- Không đồng bộ/Đang chờ
- Điều khoản khác
- Thao tác chuỗi
- Tệp vào/ra
- Ngày giờ
- Thuốc gốc
- Nullables
- Thuộc tính & Phản ánh
- Phương pháp mở rộng
- Tiêm phụ thuộc
- Lớp học một phần
- Khả năng tương tác
- Các loại ẩn danh
- Bộ dữ liệu
- Khớp mẫu
- Hàm cục bộ
- Hồ sơ
- với biểu thức
- Bộ chỉ mục và dãy
- sử dụng Tuyên bố
- Các loại tham chiếu có thể rỗng (NRT)
- Sử dụng dựa trên mẫu
- Mẫu thuộc tính
- Triển khai giao diện mặc định
- Liên kết động
1. Cấu trúc cơ bản
Tất cả các chương trình C# đều tuân theo cấu trúc cơ bản được nêu dưới đây:
using System; public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello, World!"); } }
Bắt đầu với .NET 5, các câu lệnh cấp cao nhất sẽ đơn giản hóa nội dung Program.cs:
Console.WriteLine("Hello, World");
2. Kiểu dữ liệu
C# hỗ trợ nhiều kiểu dữ liệu khác nhau như:
- Các loại giá trị: int, char và float
- Các kiểu tham chiếu: chuỗi, lớp và mảng
3. Biến
Biến là tên tượng trưng cho các giá trị:
int age = 30; // integer variable string name = "John"; // string variable double PI = 3.14159; // double for floating-point numbers bool isLoggedIn = true; // boolean variable
Sử dụng 'var' để suy luận kiểu:
var number = 5; // compiler infers type as int var message = "This is a message"; // compiler infers type as string
4. Hằng số
Các hằng số giữ các giá trị bất biến:
const double GRAVITY = 9.81; // constant for gravitational acceleration const string COMPANY_NAME = "MyCompany"; // constant company name
5. Câu lệnh có điều kiện
Kiểm soát luồng chương trình dựa trên các điều kiện:
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
6. Vòng lặp
Thực thi mã nhiều lần:
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
7. Mảng
Bộ sưu tập các phần tử có kích thước cố định:
string[] names = new string[3] { "Alice", "Bob", "Charlie" }; Console.WriteLine(names[1]); // Output: Bob (accessing element at index 1)
8. Danh sách
Bộ sưu tập động tương tự như mảng:
List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); foreach (var number in numbers) { Console.WriteLine(number); }
9. Từ điển
Cặp khóa-giá trị để liên kết dữ liệu:
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
10. Phương pháp
Đóng gói logic có thể tái sử dụng:
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}"); } }
11. Lớp & Đối tượng
Các lớp xác định bản thiết kế cho các đối tượng:
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
12. Xử lý ngoại lệ
Quản lý lỗi thời gian chạy một cách khéo léo:
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}"); }
13. Đại biểu, Sự kiện & Lambda
Đối với lập trình hướng sự kiện và xử lý phương thức:
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) } }
14. LINQ (Truy vấn tích hợp ngôn ngữ)
Khả năng truy vấn để thao tác dữ liệu:
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 } }
15. Thuộc tính
Thêm siêu dữ liệu vào các thành phần mã:
[Obsolete("Use the new DoSomethingV2 method instead.")] public void DoSomething() { // Implementation here } public void DoSomethingV2() { // New and improved implementation }
16. Không đồng bộ/Đang chờ
Để thực thi mã không chặn:
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..."); }
17. Linh tinh
Các tính năng ngôn ngữ bổ sung:
- enum, giao diện, lớp, bản ghi và cấu trúc
- động, là, as, var và nameof
18. Thao tác với chuỗi
Phương pháp xử lý chuỗi mạnh mẽ:
string.Concat(); // Combine strings string.Join(); // Join elements str.Split(); // Split string str.ToUpper(); // Convert to uppercase str.ToLower(); // Convert to lowercase
19. Tệp vào/ra
Các thao tác với tập tin:
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
20. Ngày & Giờ
Thao tác ngày và giờ:
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"); }
21. Thuốc gốc
Cấu trúc dữ liệu an toàn kiểu:
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 }
22. Nullables
Cho phép các loại giá trị là null:
int? nullableInt = null; // Nullable integer
23. Thuộc tính & Phản ánh
Xem xét nội tâm siêu dữ liệu và kiểu:
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 } }
24. Phương pháp mở rộng
Thêm phương thức vào các loại hiện có:
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! }
25. Tiêm phụ thuộc
Thiết kế mã kết hợp lỏng lẻo:
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(); }
26. Lớp học một phần
Tách một định nghĩa lớp duy nhất:
public partial class MyClass { /*...*/ } // Partial class definition
27. Khả năng tương tác
Tương tác với các ngôn ngữ khác:
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); }
28. Các loại ẩn danh
Tạo các loại không tên:csharpSao chép mã
var person = new { Name = "John", Age = 30 }; Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
29. Bộ dữ liệu
Cấu trúc dữ liệu với một số phần tử cụ thể:
(string Name, int Age) person = ("Alice", 30); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Accessing elements using Item1 and Item2
30. Kết hợp mẫu
Đơn giản hóa một số tác vụ lập trình nhất định:
object obj = new Person { Name = "Bob", Age = 25 }; if (obj is Person { Name: "Bob", Age >= 18 }) { Console.WriteLine("Bob is an adult."); }
31. Chức năng địa phương
Đóng gói logic trong các phương thức:
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}"); }
32. Hồ sơ
Cú pháp ngắn gọn cho các loại tham chiếu:
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"); } }
33. với biểu thức
Đột biến không phá hủy đối với bản ghi:
var john = new Person("John", 30); var jane = john with { Name = "Jane" }; // Non-destructive mutation
34. Bộ chỉ mục và dãy
Truy cập dữ liệu linh hoạt:
int[] arr = {0, 1, 2, 3, 4, 5}; var subset = arr[1..^1]; // Indexer and range usage
35. sử dụng Tuyên bố
Vứt bỏ các đối tượng IDisposable:
using var reader = new StreamReader("file.txt"); // using declaration
36. Các loại tham chiếu có thể vô hiệu hóa (NRT)
Tránh các ngoại lệ tham chiếu null:
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"); } }
37. Sử dụng dựa trên mẫu
Các mẫu khác trong câu lệnh sử dụng:
public ref struct ResourceWrapper { /*...*/ } // Resource wrapper using var resource = new ResourceWrapper(); // Pattern-based using
38. Các mẫu thuộc tính
Giải cấu trúc các đối tượng trong khớp mẫu:
if (obj is Person { Name: "John", Age: var age }) { /*...*/ } // Property pattern matching
39. Triển khai giao diện mặc định
Các giao diện có triển khai phương thức mặc định:
public interface IPerson { /*...*/ } // Interface with default method public class MyClass : IPerson { /*...*/ } // Class implementing interface
40. Ràng buộc động
Độ phân giải loại thời gian chạy:
dynamic d = 5; // Dynamic binding d = "Hello"; // No compile-time type checking
Phần kết luận
Bảng Cheat C# có cấu trúc này kết thúc bằng các chủ đề và kỹ thuật nâng cao, cung cấp tài liệu tham khảo toàn diện cho các nhà phát triển nhằm nâng cao kỹ năng lập trình C# của họ. Để biết các ví dụ chi tiết và khám phá thêm, hãy tham khảo các phần cụ thể được nêu trong hướng dẫn này. Chúc mừng mã hóa!
Lập trình C#🚀
Cảm ơn bạn đã là thành viên của cộng đồng C#! Trước khi bạn đi:
Nếu bạn đã làm được đến mức này, hãy thể hiện sự đánh giá cao của bạn bằng một tràng pháo tay và theo dõi tác giả! 👏️️
Theo dõi chúng tôi: X | LinkedIn | Dev.to | Nút băm | Bản tin | tumblr
Truy cập các nền tảng khác của chúng tôi: GitHub | Instagram | Tiktok | Quora | Daily.dev
Lấy cảm hứng từ: https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants
Cũng được xuất bản ở đây