Using static void Main() method from base class as a program's entry point

前端 未结 2 1205
一向
一向 2021-01-15 17:15

I would like to abstract some program logic to a base class for executing a command-line program (functionality similar to what this question was requesting).

in oth

相关标签:
2条回答
  • 2021-01-15 17:26

    I think the problem is that BaseClass is generic. In order to call main you have to supply a type argument, so which type should the system choose to call this method? Ofcourse it can't make random choices so this is illegal.

    I found this in C# 5.0 Language Specification in 3.1 Application Startup

    The application entry point method may not be in a generic class declaration.

    0 讨论(0)
  • 2021-01-15 17:39

    As was eventually disclosed during the commenting of the other answer, your BaseProgram<T> class is in a different assembly from the one you are trying to execute. The entry point of an assembly has to be in that assembly.

    To do otherwise is like giving someone a key and telling them that's the key to your house's front door. Except the key is actually for some other completely different house's front door, so when they show up at your house it does them no good.

    If you want to use the BaseProgram<T>'s Main() method, you need to delegate to it. For example, in your own assembly:

    static class Program
    {
        public static int Main(string[] args)
        {
            return BaseProgram<string>.Main(args);
        }
    }
    

    Note that for static types or static members of types, there's no need to actually inherit the base type, since you just invoke it via the actual type name instead of an instance reference.

    0 讨论(0)
提交回复
热议问题