包括的な C# チートシートは、開発者が C# プログラミングに関連する主要な構文と概念を習得できるように設計されています。 コンテンツ 基本構造 データ型 変数 定数 条件文 ループ 配列 リスト 辞書 メソッド クラスとオブジェクト 例外処理 デリゲート、イベント、ラムダ LINQ (言語統合クエリ) 属性 非同期/待機 その他 文字列の操作 ファイルI/O 日付時刻 ジェネリック Nullable 属性と反射 拡張メソッド 依存関係の注入 部分クラス 相互運用性 匿名型 タプル パターンマッチング ローカル機能 記録 式付き インデクサーと範囲 宣言の使用 Null 許容参照型 (NRT) パターンベースの使用 プロパティパターン デフォルトのインターフェース実装 動的バインディング 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. デリゲート、イベント、Lambda イベント駆動型プログラミングとメソッド処理の場合: 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. Nullable 値の型を 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 リンクトイン 開発者へ ハッシュノード ニュースレター タンブラー 他のプラットフォームにアクセスしてください: | | | | GitHub インスタグラム ティックトック クオラ Daily.dev インスピレーション源: https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants でも公開されています ここ