導入
これまでのメンバーは「オブジェクトごと」に存在しました。一方、クラス全体で1つだけ共有したいデータや、オブジェクトを作らずに使いたいユーティリティ関数にはstaticを使います。
図解
flowchart TB
S["static メンバー<br/>クラスに1つだけ共有"] --- I1["インスタンスA"]
S --- I2["インスタンスB"]
U["MathUtil.Square(5)<br/>new せずに呼べる"] --> S
style S fill:#e8f5e9
サンプル
// static メソッドは new せずクラス名から直接呼ぶ(Console.WriteLine もその一例)
Console.WriteLine(MathUtil.Square(5)); // 25
// static フィールドはクラス全体で共有される
var a = new Visitor();
var b = new Visitor();
Console.WriteLine(Visitor.Count); // 2(作られた総数を共有カウント)
static class MathUtil
{
public static int Square(int n) => n * n;
}
class Visitor
{
public static int Count = 0; // 全インスタンスで共有
public Visitor()
{
Count++; // 生成のたびに共有カウンタを増やす
}
}
staticメンバーはオブジェクトごとではなく、クラスに1つだけ存在するstaticメソッドはnewせずにクラス名.メソッド()で呼べる(Console.WriteLineもそう)- 「全体で共有するカウンタ」「道具箱的な関数」に向く
演習
Console.WriteLine(Calculator.Add(3, 4)); // 7
// TODO: new せずに使える static メソッド Add(a, b) を持つ
// static クラス Calculator を定義してください
___
- 期待される出力:
7
ヒント1を見る
static class Calculator { public static int Add(int a, int b) => a + b; }
ヒント2を見る
Console.WriteLine(Calculator.Add(3, 4)); static class Calculator { public static int Add(int a, int b) => a + b; }
まとめ
staticメンバーはクラスに1つだけ共有されるstaticメソッドはnewせずクラス名から直接呼べる- 共有カウンタやユーティリティ関数に使う
次回: すべてのクラスの親objectと、そのEquals/GetHashCodeの意味です。