简体   繁体   English

是否可以在c#类中添加main方法并像在Java中那样运行它?

[英]Is it possible to add main method in c# class and run it like in Java?

Basically i know when in Java I add main method then I can run it independently on my project. 基本上我知道在Java中何时添加main方法,然后就可以在项目上独立运行它了。 But I cannot figure out how to do it in Visual Studio :(. 但是我无法弄清楚如何在Visual Studio中进行:(。

Yes, you can define a method that is called Main in C# too. 是的,您也可以在C#中定义一个称为Main的方法。

According to MSDN : 根据MSDN

The Main method is the entry point of a C# console application or windows application. Main方法是C#控制台应用程序或Windows应用程序的入口点。 There can only be one entry point in a C# program. C#程序中只能有一个入口点。 If you have more than one class that has a Main method, you must compile your program with the /main compiler option to specify which Main method to use as the entry point. 如果有一个以上的类具有Main方法,则必须使用/ main编译器选项编译程序,以指定将哪个Main方法用作入口点。

public class Program
{
    private void Main(string[] args)
    {
        // This code will run on your program's startup
    }
}

In Java, each class will generate a .class file before it is compiled into a JAR or whatever binary format used to deploy it. 在Java中,每个类都会在编译为JAR或用于部署它的任何二进制格式之前生成一个.class文件。 This allows the Java executable to run a single class when it contains a main method. 当Java可执行文件包含main方法时,它可以运行单个类。 Unfortunately, the smallest binary format of a runnable C# application is a .exe file. 不幸的是,可运行的C#应用​​程序的最小二进制格式是.exe文件。 A single executable project will output only one .exe file, this means each project may only have a single Main method. 单个可执行项目将仅输出一个.exe文件,这意味着每个项目可能只有一个Main方法。

What you can do is create a Main method in your class and rename the original Main method to Main2 or something like that, then run your project to see the results. 您可以做的是在类中创建Main方法,并将原始Main方法重命名为Main2或类似的名称,然后运行项目以查看结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM