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

久未见 提交于 2019-12-01 08:19:11

问题


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 other words, something like this:

public abstract class BaseProgram<T>
{
    public static void Main(string[] args)
    {
        Console.WriteLine(typeof(T));
    }
}

public class Program : BaseProgram<string>
{
}

It is important to note that BaseProgram is in a different assembly.

This, however, does not work. The static void Main(string[] args) method must be in the derived class. Can anyone explain why that is? After all, the following is totally 'legal':

Program.Main(null);
BaseProgram<string>.Main(null);

and will output:

> System.String
> System.String

What I would like to know: are there any documented reasons for this outcome?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27050960/using-static-void-main-method-from-base-class-as-a-programs-entry-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!