`static` キーワード
メニューを表示するにはスワイプしてください
何度も目にしたことがあるかもしれない重要なキーワードが、static キーワードです。C# 基礎コースでは、static はグローバル変数(特定のメソッドの外側にある変数)を定義する際に使用されると説明されていました。
index.cs
1234567891011using System; class ConsoleApp { static int val = 10; static void Main() { Console.WriteLine($"The value is {val}"); } }
当時は、読者がオブジェクトやクラスについて知識がないことを想定していたため、static キーワードを説明する便利な方法でした。しかし、今コードを見ると、val は実際には ConsoleApp クラスのフィールドであることに気付くかもしれません。ただし、ConsoleApp クラスは通常作成するクラスとは少し異なります。ConsoleApp はプログラム自体を表しており、ConsoleApp のオブジェクトは存在しません。この部分については後ほど再度説明します。
クラスは設計図、つまり空の殻のようなものであり、通常は自分自身でデータを持ちません。その設計図を使ってオブジェクトを作成し、そのオブジェクトからデータを保存・アクセスするという仕組みです(前述の通り)。
index.cs
12345678910111213141516171819202122232425262728using System; class Complex { public int real; public int img; public Complex(int real, int img) { this.real = real; this.img = img; } } class ConsoleApp { static int val = 10; static void Main() { Complex c = new Complex(5, 10); // We can use and update the field of 'c' which is an instance. Console.WriteLine(c.real); c.real = 7; Console.WriteLine(c.real); } }
クラス内であっても、これらのフィールドへアクセスする際は、オブジェクトを通じてアクセスしています。たとえばコンストラクター内では、コンストラクターメソッドを呼び出したオブジェクトから渡されたデータを基本的に使用しています。
index.cs
12345678public Complex(int real, int img) { // 'int real' and 'int img' contain the data which was passed // 'this.real' refers to the 'real' field of the object which is calling this constructor // same is the case for 'this.img' this.real = real; this.img = img; }
同様に、他のメソッドでもフィールドへアクセスする場合、基本的にはそのメソッドを呼び出すオブジェクトのフィールドにアクセスしており、クラス自体のフィールドではありません。なぜなら、通常クラス自体はデータを持たないためです。
しかし、クラスに直接データを格納し、オブジェクトを作成せずにプロパティへアクセスできる方法があります。それは、そのフィールドやメソッドを static にすることです。
index.cs
123456789101112131415161718192021222324252627282930313233343536373839using System; class Complex { public int real; public int img; // A static field can contain data // It is set to private because we don't want it to be manually modifiable from outside // This will track the total number of 'Complex' objects created private static int numbers = 0; public Complex(int real, int img) { this.real = real; this.img = img; numbers += 1; } // A static method // A static method or field can be accessed using the 'ClassName.PropertyName' syntax (see below) public static int getTotalComplexNumbers() { return numbers; } } class ConsoleApp { static void Main() { Console.WriteLine(Complex.getTotalComplexNumbers()); // 0 new Complex(1, 2); Console.WriteLine(Complex.getTotalComplexNumbers()); // 1 new Complex(2, 3); Console.WriteLine(Complex.getTotalComplexNumbers()); // 2 } }
ConsoleApp やプログラム自体を表すメインクラスは、オブジェクトを持つことができないため、そのメソッドやフィールドは static にする必要があります。このため、Main メソッドも static になっています。
index.cs
1234static void Main() { // code }
1. クラスは直接データを保存できますか?
2. value フィールドを変更する正しい構文はどれですか?
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください