インスタンスメソッドと静的メソッドに同じメソッド名をつける
インスタンスメソッドと静的メソッドのそれぞれに同じ名前を付けることが出来ます。ただし、メソッドの引数は異なるようにする必要があります。
たとえば、以下のサンプルコードでは、インスタンスメソッドと静的メソッドいずれも Hello という名前で定義しています。いずれも引数を取りません。このコードはコンパイルできません。
// test.cs using System; class Foo { public void Hello() { Console.WriteLine("instance hello"); } public static void Hello() { Console.WriteLine("class hello"); } } class Program { static void Main() { new Foo().Hello(); Foo.Hello(); } }
$ mcs test.cs test.cs(9,24): error CS0111: A member `Foo.Hello()' is already defined. Rename this member or use different parameter types test.cs(5,17): (Location of the symbol related to previous error) Compilation failed: 1 error(s), 0 warnings
メソッド名を変更するか、もしくは引数が異なるように変更する必要があります。
クラスメソッドに引数を追加すると、今度はコンパイルが通ります。
// test.cs using System; class Foo { public void Hello() { Console.WriteLine("instance hello"); } public static void Hello(int n) { // <- 引数を追加した Console.WriteLine("class hello"); } } class Program { static void Main() { new Foo().Hello(); Foo.Hello(10); } }
コンパイルおよび実行結果です。
$ mcs test.cs $ mono test.exe instance hello class hello