クラスの定義
public class User
{
// フィールド
private string _name;
private int _age;
// コンストラクタ
public User(string name, int age)
{
_name = name;
_age = age;
}
// プロパティ
public string Name
{
get { return _name; }
set { _name = value; }
}
// 自動実装プロパティ
public string Email { get; set; }
// 読み取り専用プロパティ
public int Age => _age;
// メソッド
public string Introduce()
{
return $"私は{_name}です。{_age}歳です。";
}
}
使用例
var user = new User("太郎", 25);
user.Email = "taro@example.com";
Console.WriteLine(user.Introduce());
プロパティ
public class Product
{
// 自動実装プロパティ
public string Name { get; set; }
// 初期値付き
public int Stock { get; set; } = 0;
// 読み取り専用
public DateTime CreatedAt { get; } = DateTime.Now;
// init専用(C# 9以降)
public string Id { get; init; }
// バリデーション付き
private decimal _price;
public decimal Price
{
get => _price;
set => _price = value >= 0 ? value : throw new ArgumentException("価格は0以上");
}
}
継承
public class Animal
{
public string Name { get; set; }
public virtual void Speak()
{
Console.WriteLine("...");
}
}
public class Dog : Animal
{
public string Breed { get; set; }
public override void Speak()
{
Console.WriteLine("ワンワン!");
}
}
public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("ニャー!");
}
}
// 使用
Animal dog = new Dog { Name = "ポチ" };
dog.Speak(); // ワンワン!
抽象クラス
public abstract class Shape
{
public abstract double Area();
public void PrintArea()
{
Console.WriteLine($"面積: {Area()}");
}
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width * Height;
}
}
インターフェース
public interface ILogger
{
void Log(string message);
void LogError(string message);
}
public interface IDisposable
{
void Dispose();
}
public class FileLogger : ILogger, IDisposable
{
private StreamWriter _writer;
public FileLogger(string path)
{
_writer = new StreamWriter(path);
}
public void Log(string message)
{
_writer.WriteLine($"[INFO] {message}");
}
public void LogError(string message)
{
_writer.WriteLine($"[ERROR] {message}");
}
public void Dispose()
{
_writer?.Dispose();
}
}
record(C# 9以降)
// 不変データ型を簡潔に定義
public record User(string Id, string Name, int Age);
// 使用
var user = new User("1", "太郎", 25);
Console.WriteLine(user); // User { Id = 1, Name = 太郎, Age = 25 }
// with式でコピー
var user2 = user with { Name = "花子" };
// 値の等価性
var user3 = new User("1", "太郎", 25);
Console.WriteLine(user == user3); // true
staticメンバー
public class Counter
{
private static int _count = 0;
public Counter()
{
_count++;
}
public static int Count => _count;
public static void Reset()
{
_count = 0;
}
}
拡張メソッド
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
public static string Truncate(this string str, int maxLength)
{
if (str.Length <= maxLength) return str;
return str.Substring(0, maxLength) + "...";
}
}
// 使用
string name = "太郎";
bool isEmpty = name.IsNullOrEmpty(); // false
string truncated = "長い文字列です".Truncate(5); // "長い文字列..."
ジェネリクス
public class Box<T>
{
public T Value { get; set; }
public Box(T value)
{
Value = value;
}
}
public class Repository<T> where T : class, new()
{
private List<T> _items = new List<T>();
public void Add(T item)
{
_items.Add(item);
}
public T CreateNew()
{
return new T();
}
}
まとめ
- クラスはフィールド、プロパティ、メソッドで構成
virtualとoverrideでメソッドをオーバーライドabstractクラスは直接インスタンス化できないinterfaceで契約を定義recordで不変データ型を簡潔に定義- 拡張メソッドで既存の型にメソッドを追加
次回は例外処理と非同期について学びます。