使用基类中的静态void Main()方法作为程序的入口点 [英] Using static void Main() method from base class as a program's entry point

查看:88
本文介绍了使用基类中的静态void Main()方法作为程序的入口点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些程序逻辑抽象到基类中以执行命令行程序(功能类似于)。

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>
{
}

请务必注意,BaseProgram与其他程序不同

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

但是,这不起作用。 静态void Main(string [] args)方法必须在派生类中。谁能解释为什么?毕竟,以下内容完全是合法的:

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);

,将输出:

> System.String
> System.String

我想知道的内容:是否有记录在案导致这种结果的原因?

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

推荐答案

正如在其他答案的评论中最终披露的那样,您的 BaseProgram< ; T> 类与您尝试执行的程序不在同一程序集中。程序集的入口点必须在该程序集的 中。

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.

如果要使用 BaseProgram< T> Main()方法,您需要委派给它。例如,在您自己的程序集中:

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.

这篇关于使用基类中的静态void Main()方法作为程序的入口点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆