포괄적인 C# 치트 시트는 개발자가 C# 프로그래밍과 관련된 주요 구문과 개념을 익히는 데 도움을 주기 위해 설계되었습니다. 내용물 기본 구조 데이터 유형 변수 상수 조건문 루프 배열 기울기 사전 행동 양식 클래스 및 객체 예외 처리 대리인, 이벤트 및 람다 LINQ(언어 통합 쿼리) 속성 비동기/대기 여러 가지 잡다한 문자열 조작 파일 I/O 날짜 시간 제네릭 Nullable 속성 및 반사 확장 방법 의존성 주입 부분 수업 상호 운용성 익명 유형 튜플 패턴 매칭 로컬 기능 기록 표현식 포함 인덱서 및 범위 선언 사용 NRT(Nullable 참조 유형) 패턴 기반 사용 속성 패턴 기본 인터페이스 구현 동적 바인딩 1. 기본 구조 모든 C# 프로그램은 아래에 설명된 기본 구조를 따릅니다. using System; public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } .NET 5부터 최상위 문은 Program.cs 콘텐츠를 단순화합니다. Console.WriteLine("Hello, World"); 2. 데이터 유형 C#은 다음과 같은 다양한 데이터 형식을 지원합니다. 값 유형: int, char 및 float 참조 유형: 문자열, 클래스, 배열 3. 변수 변수는 값에 대한 기호 이름입니다. 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 4. 상수 상수는 변경할 수 없는 값을 보유합니다. const double GRAVITY = 9.81; // constant for gravitational acceleration const string COMPANY_NAME = "MyCompany"; // constant company name 5. 조건문 조건에 따라 프로그램 흐름을 제어합니다. 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. 루프 코드를 반복적으로 실행합니다. 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. 배열 고정 크기 요소 컬렉션: string[] names = new string[3] { "Alice", "Bob", "Charlie" }; Console.WriteLine(names[1]); // Output: Bob (accessing element at index 1) 8. 목록 배열과 유사한 동적 컬렉션: List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); foreach (var number in numbers) { Console.WriteLine(number); } 9. 사전 데이터 연결을 위한 키-값 쌍: 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. 방법 재사용 가능한 논리를 캡슐화합니다. 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. 클래스와 객체 클래스는 객체에 대한 청사진을 정의합니다. 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. 예외 처리 런타임 오류를 적절하게 관리합니다. 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. 대리인, 이벤트 및 람다 이벤트 중심 프로그래밍 및 메소드 처리의 경우: 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(언어 통합 쿼리) 데이터 조작을 위한 쿼리 기능: 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. 속성 코드 요소에 메타데이터를 추가합니다. [Obsolete("Use the new DoSomethingV2 method instead.")] public void DoSomething() { // Implementation here } public void DoSomethingV2() { // New and improved implementation } 16. 비동기/대기 비차단 코드 실행의 경우: 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. 기타 추가 언어 기능: 열거형, 인터페이스, 클래스, 레코드 및 구조체 동적, is, as, var 및 nameof 18. 문자열 조작 강력한 문자열 처리 방법: string.Concat(); // Combine strings string.Join(); // Join elements str.Split(); // Split string str.ToUpper(); // Convert to uppercase str.ToLower(); // Convert to lowercase 19. 파일 I/O 파일 작업: 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. 날짜 및 시간 날짜 및 시간 조작: 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. 제네릭 유형이 안전한 데이터 구조: 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. 널 입력 가능 값 유형이 null이 되도록 허용합니다. int? nullableInt = null; // Nullable integer 23. 속성 및 반사 메타데이터 및 유형 검사: 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. 확장 방법 기존 유형에 메서드를 추가합니다. 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. 의존성 주입 느슨하게 결합된 코드 디자인: 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. 부분 수업 단일 클래스 정의 분할: public partial class MyClass { /*...*/ } // Partial class definition 27. 상호 운용성 다른 언어와의 상호 운용성: 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. 익명 유형 이름 없는 유형 만들기:csharp코드 복사 var person = new { Name = "John", Age = 30 }; Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); 29. 튜플 특정 개수의 요소를 포함하는 데이터 구조: (string Name, int Age) person = ("Alice", 30); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Accessing elements using Item1 and Item2 30. 패턴 매칭 특정 프로그래밍 작업을 단순화합니다. object obj = new Person { Name = "Bob", Age = 25 }; if (obj is Person { Name: "Bob", Age >= 18 }) { Console.WriteLine("Bob is an adult."); } 31. 로컬 기능 메소드 내에 로직을 캡슐화합니다. 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. 기록 참조 유형에 대한 간결한 구문: 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. 표현식 사용 레코드에 대한 비파괴적 변형: var john = new Person("John", 30); var jane = john with { Name = "Jane" }; // Non-destructive mutation 34. 인덱서와 범위 유연한 데이터 액세스: int[] arr = {0, 1, 2, 3, 4, 5}; var subset = arr[1..^1]; // Indexer and range usage 35. 선언 사용 IDisposable 개체를 삭제합니다. using var reader = new StreamReader("file.txt"); // using declaration 36. Null 허용 참조 유형(NRT) 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. 패턴 기반 활용 using 문의 추가 패턴: public ref struct ResourceWrapper { /*...*/ } // Resource wrapper using var resource = new ResourceWrapper(); // Pattern-based using 38. 속성 패턴 패턴 일치에서 객체를 분해합니다. if (obj is Person { Name: "John", Age: var age }) { /*...*/ } // Property pattern matching 39. 기본 인터페이스 구현 기본 메소드 구현과의 인터페이스: public interface IPerson { /*...*/ } // Interface with default method public class MyClass : IPerson { /*...*/ } // Class implementing interface 40. 동적 바인딩 런타임 유형 해결: dynamic d = 5; // Dynamic binding d = "Hello"; // No compile-time type checking 결론 이 구조화된 C# 치트 시트는 고급 주제와 기술로 마무리되어 C# 프로그래밍 기술 향상을 목표로 하는 개발자에게 포괄적인 참조 자료를 제공합니다. 자세한 예와 추가 탐색을 보려면 이 가이드에 설명된 특정 섹션을 참조하세요. 즐거운 코딩하세요! C# 프로그래밍🚀 C# 커뮤니티의 일원이 되어주셔서 감사합니다! 가기 전에: 여기까지 잘 따라오셨다면 박수로 감사의 인사를 전하고, 작가님을 팔로우해주세요! 👏️️ 팔로우하세요: | | | | | X 링크드인 Dev.to 해시노드 뉴스레터 텀블러 다른 플랫폼을 방문해보세요: | | | | GitHub 인스타그램 틱톡 쿼라 Daily.dev 영감을 받은 사람: https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants 게시됨 여기에도