基本的な方法は次のとおりです。
[access modifier?] [static?] [return type or void] [name] ([parameters?])
いくつかの余分な部分がありますが、それはあなたの出発点です。
アクセス修飾子
それらのいくつかは、修飾子を付けたものが何であれ、どのクラスがアクセスできるか(呼び出すことができるか)を制御するアクセス修飾子です。
// Anyone can call me
public int SomeMethod() { return 1; }
// Only classes in the same assembly (project) can call me
internal int SomeMethod() { return 1; }
// I can only be called from within the same class
private int SomeMethod() { return 1; }
// I can only be called from within the same class, or child classes
protected int SomeMethod() { return 1; }
静的
Static
メソッド/変数がクラスのすべてのインスタンスによって共有されることを意味します。上からのアクセス修飾子と組み合わせることができます。
public class Test
{
static int a = 0;
public int SomeMethod() { a = a + 1; return a; }
}
Test t1 = new Test();
t1.SomeMethod(); // a is now 1
Test t2 = new Test();
t2.SomeMethod(); // a is now 2
// If 'a' wasn't static, each Test instance would have its own 'a'
空所
void
何も返さないメソッドがあることを意味します。
public void SomeMethod()
{
/* I don't need to return anything */
}
const
const
変数を変更できないことを意味します。
const int LIFE = 42;
// You can't go LIFE = 43 now