简体   繁体   中英

Can I have two entry points in C#

Would it be possible to use two entry points in C# instead of just having the one. For example when I have this:

using System;
namespace learning
{
    class cool
    {
        static void Main(string[] args)
        {
        }
    }
}

Would it be possible to have another entry point such as secondary that the program executes once the main entry point has finished.

You may want to do something like this:

class Program {
    public static void EntryPoint1(string[] args) {
        // Code
    }
    public static void EntryPoint2(string[] args) {
        // Code
    }

    public static void Main(string[] args) {
        EntryPoint1(args);
        EntryPoint2(args);
    }
}

Just make sure to not modify args during EnteryPoint1 or if you want to, clone them like this:

class Program {
    public static void EntryPoint1(string[] args) {
        // Code
    }
    public static void EntryPoint2(string[] args) {
        // Code
    }

    public static void Main(string[] args) {
        EntryPoint1(args.Clone());
        EntryPoint2(args.Clone());
    }
}

In C#, you specify the entry point using the /main: compiler option. Imagine that the code containing containing two main() methods as follow :

namespace Application {
class ClassA {
    static void main () {
        // Code here
    }
}

class ClassB {
    static void main () {
        // Code here
    }
}

To use ClassA.main() as your entry point, you would specify the following when compiling:

csc /main:Application.ClassA hello.cs

You can only have a single entry point, but you can write two separate methods, call the first one, and then the second one. You will achieve what you're describing.

using System;
namespace learning
{
    class cool
    {
        static void Main(string[] args)
        {
            PartOne();
            PartTwo();
        }

        void PartOne() {
            // Something happens here
        }

        void PartTwo() {
            // Something else happens here
        }
    }
}

Additionally (depending on how the program starts up) you can send in arguments to specify which method you want to execute (if you don't need both of them to execute). Then you can just do an "if/else" statement that will decide which method to run depending on the arguments passed into Main

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