简体   繁体   中英

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. But I cannot figure out how to do it in Visual Studio :(.

Yes, you can define a method that is called Main in C# too.

According to MSDN :

The Main method is the entry point of a C# console application or windows application. There can only be one entry point in a C# program. 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.

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. This allows the Java executable to run a single class when it contains a main method. Unfortunately, the smallest binary format of a runnable C# application is a .exe file. A single executable project will output only one .exe file, this means each project may only have a single Main method.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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