我尝试在C#中创建public void Main()
,它提示说没有找到静态的void Main。
那么什么是Main
是静态的意思呢?我知道用public static void Main()
可以正常工作。
为什么Main
必须是static
的呢?
我尝试在C#中创建public void Main()
,它提示说没有找到静态的void Main。
那么什么是Main
是静态的意思呢?我知道用public static void Main()
可以正常工作。
为什么Main
必须是static
的呢?
你需要一个程序的入口点。静态意味着你可以调用函数而不必实例化一个类的对象/实例。这有点像"先有鸡还是先有蛋"的问题......在进入程序之前,你不能实例化一个对象。
一个静态方法可以在不实例化对象的情况下被调用。因此,main()
需要是静态的才能允许它成为你的程序入口。
正如David所说,你只需在函数定义中添加关键字 static
即可更改它。值得研究静态(类)方法与实例方法之间的区别,了解这些差异有时会很有用。
Main
方法之前实例化许多对象。您可以通过将静态构造函数放入包含 Main
方法的类中来手动触发此过程。抱歉,我意识到这个帖子已经超过一年了,但我认为这仍然相关。 - Konrad RudolphApplication startup occurs when the execution environment calls a designated method, which is referred to as the application's entry point. This entry point method is always named
Main
, and shall have one of the following signatures:
static void Main() {…} static void Main(string[] args) {…} static int Main() {…} static int Main(string[] args) {…}
As shown, the entry point can optionally return an
int
value. This return value is used in application termination (§10.2).
注意:以上引用自第4版,现已标记为“历史”。当前版本的措辞不同。
除此之外,名称Main
可以更改为其他名称。在这种情况下,必须添加编译器选项,告诉C#编译器将不同的方法标记为程序的入口点。
类中有两种方法类型:
// Example of static and non-static methods and how to call
namespace TestStaticVoidMain
{
class Program
{
Static Void Main(string[] args)
{
// Instantiate or create object of the non-static method:
Exam ob = new Exam();
// Call the instance:
ob.Test1();
// Directly the call the static method by its class:
Exam.Test2();
Console.ReadKey();
}
}
class Exam
{
public void Test1()
{
Console.WriteLine("This is a non-static method");
}
public static void Test2()
{
Console.WriteLine("This is a static method");
}
}
}
1. 静态方法:
调用静态方法(函数)时,我们不需要实例化或创建该方法的对象。我们不能使用new
关键字,因为当类被加载和编译时,static
关键字默认实例化或创建该类方法的对象,所以我们直接调用一个静态方法。
关于static void Main(string[] args)
,我们已经讨论了static
。剩下的是void Main(string[] args)
。void
是一种不返回任何值的数据类型。Main()
是C#程序执行的标准入口点。可选参数string[] args
接收程序运行时带有的可选“命令行”参数。
2. 非静态方法:
要调用非静态方法,我们必须实例化或创建该类方法的对象,使用关键字new
来调用类的方法(函数)。
如果一个名为Test
的类有一个名为show()
的非静态方法,那么它将如何调用一个实例:
// to call non-static method
Test ob=new Test();
ob.show();
public static void Main( [[params]] )
{
var mainObject = new MainObject();
mainObject.Main( [[params]] );
}
为系统包含自己的静态方法可能带来一些潜在的好处,该方法大致如下:
public static void SysMain( [[params]] )
{
using (Application app = new UserApp( [[params]] )) // UserApp derives from Application
{
app.Start(); // Virtual method
app.AllowNext(); // Base method--see text
app.Run(); // Abstract method
}
}
在这里,app.AllowNext()
是一个方法,用于与在基本上同时启动的其他应用程序实例协调,以确保重复尝试在后台启动应用程序的Start
调用严格按顺序处理。但如果没有这样一个协调方案,实际上要求框架在运行应用程序之前构造应用程序对象并没有太多好处。这种成本不会很大,但是如果没有任何潜在可识别的好处,那么接受甚至微不足道的成本也没有太多意义。
static void Main(){..}
但也可以使用标题声明:
static void Main(string[] args){..}
你可以声明带有返回类型 int 的 Main(而不是 void)—如果一个应用程序由另一个应用程序执行并需要向该其他应用程序返回成功或失败的指示,则这可能很有用。
主函数应该是静态的,这样它会首先加载并成为程序的入口点,因此主函数的静态性非常重要。