静态方法概述C#入门经典解析
在C#中,静态方法(也称为类方法)是一种无需实例化对象即可被调用的方法。此类方法使用 static
关键字声明,并仅能访问静态变量。访问非静态变量的任何尝试都将导致编译错误。静态方法也无法被重写成非静态方法。
示例:
以下是静态方法的示例代码。
public class GeneralFunction {
public static int AddUp(int x, int y) {
// 静态方法
return x + y;
}
}
public class UseGeneral {
public void method() {
int c = GeneralFunction.AddUp(9, 10); // 调用静态方法
System.Console.WriteLine("addUp() gives " + c);
}
}
在 UseGeneral
类的 method
方法中,通过 类名.方法名
的方式直接调用 GeneralFunction
类中的静态方法 AddUp
,无需实例化 GeneralFunction
对象。这是因为静态方法依赖于类而非具体对象。
为什么 Main
是静态的?
Main
方法作为C#应用程序的入口点,必须在任何类实例化之前就被调用。因此,它也被声明为静态方法。
4.81MB
文件大小:
评论区