R.V*_*tor 4 c# methods static-methods public-method
我有一个问题:这些方法类型有什么区别?
Static , Public , Internal , Protected , const , void
Run Code Online (Sandbox Code Playgroud)
对不起,我的问题对于专业人士来说可能看起来很尴尬,但我真的想了解它们的区别,顺便说一下我搜索和阅读有关它们的文章,但它们都很大而且没有很好地描述,我只需要一个很好的例子,我可以制作决定每次我做一个函数,因为我总是从私有空开始........
Mat*_*ell 21
您的基本方法如下:
[access modifier?] [static?] [return type or void] [name] ([parameters?])
Run Code Online (Sandbox Code Playgroud)
还有一些额外的零碎,但这是你的开始.
访问修饰符
其中一些是访问修饰符,它控制哪些类可以访问(可以调用)任何你放置修饰符的类.
// 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; }
Run Code Online (Sandbox Code Playgroud)
静态的
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'
Run Code Online (Sandbox Code Playgroud)
空虚
void 只是意味着你有一个不返回任何东西的方法:
public void SomeMethod()
{
/* I don't need to return anything */
}
Run Code Online (Sandbox Code Playgroud)
常量
const 表示无法修改变量:
const int LIFE = 42;
// You can't go LIFE = 43 now
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18015 次 |
| 最近记录: |