포괄적 인 C# 치트 시트는 개발자가 C# 프로그래밍과 관련된 주요 구문 및 개념을 마스터하는 데 도움이되도록 설계되었습니다.
기본 구조
데이터 유형
변수
상수
조건부 진술
루프
배열
기울기
사전
행동 양식
수업 및 물체
예외 처리
대표, 이벤트 및 람다
LINQ (언어 통합 쿼리)
속성
비동기/대기
여러 가지 잡다한
문자열 조작
파일 I/O
날짜 및 시간
제네릭
널리블
속성 및 반사
확장 방법
의존성 주입
부분 수업
상호 운용성
익명 유형
튜플
패턴 매칭
지역 기능
기록
표현으로
인덱서 및 범위
선언 사용
무효 기준 유형 (NRT)
패턴 기반 사용
속성 패턴
기본 인터페이스 구현
동적 바인딩
모든 C# 프로그램은 아래에 요약 된 기본 구조를 따릅니다.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
.NET 5로 시작하여 최상위 문장은 프로그램을 단순화합니다 .CS 컨텐츠 :
Console.WriteLine("Hello, World");
C#은 다음과 같은 다양한 데이터 유형을 지원합니다.
값 유형 : int, char, float
참조 유형 : 문자열, 클래스, 배열
변수는 값에 대한 상징적 이름입니다.
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...");
}
추가 언어 기능 :
열거, 인터페이스, 클래스, 레코드, 구조
동적, var, nameof입니다
강력한 문자열 처리 방법 :
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);
}
이름없는 유형 만들기 : Csharpcopy 코드
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
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");
}
}
사용 명령문의 더 많은 패턴 :
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# 프로그래밍 기술을 향상시키기위한 개발자에게 포괄적 인 참조를 제공합니다. 자세한 예제 및 추가 탐색은이 안내서에 요약 된 특정 섹션을 참조하십시오. 행복한 코딩!
영감 : https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants