你的基本方法有以下几点:
[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 int LIFE = 42;
// You can't go LIFE = 43 now
可能重复的http://stackoverflow.com/a/2521492/1495442 – Ria 2012-07-30 10:57:32
downvotes似乎有点苛刻。也许我可以理解“接近”的选票,但这似乎是一个真诚的问题,由无法理解现有答案的人来解决。当然,我被接受的答案偏向于:-),因为它可能只是为我所知道的所有人躲避作业,但我今天要把我的乐观主义眼镜放在眼里。 – 2012-07-30 11:20:58