为什么在 C# 中,控制台应用程序,在默认的“程序”类中,所有方法都必须是静态的
static void Main(string[] args)
最佳答案
成员函数不必是静态的;但如果它们不是静态的,则需要您实例化一个 Program
对象才能调用成员方法。
使用静态方法:
public class Program
{
public static void Main()
{
System.Console.WriteLine(Program.Foo());
}
public static string Foo()
{
return "Foo";
}
}
没有静态方法(换句话说,要求您实例化 Program
):
public class Program
{
public static void Main()
{
System.Console.WriteLine(new Program().Foo());
}
public string Foo() // notice this is NOT static anymore
{
return "Foo";
}
}
Main
必须是静态的,否则您必须告诉编译器如何实例化 Program
类,这可能是也可能不是微不足道的任务。
关于时间:: console application - static methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1685692/