C# 在WinForm应用程序中将入口点移动到DLL

C# 在WinForm应用程序中将入口点移动到DLL,c#,dll,entry-point,C#,Dll,Entry Point,我正试图找出一种方法,在我的WinForm应用程序加载之前预处理一些事情。我尝试将静态void Main()放在类库项目中的表单中,并从Program.cs中将其注释掉。生成编译时错误:“…不包含适合入口点的静态“Main”方法”。这是有意义的,因为程序没有加载,DLL也没有加载 所以问题是,有没有办法做到这一点?我希望DLL中的表单能够确定使用哪个表单启动应用程序: [STAThread] static void Main() { Application.EnableVisualStyl

我正试图找出一种方法,在我的WinForm应用程序加载之前预处理一些事情。我尝试将静态void Main()放在类库项目中的表单中,并从Program.cs中将其注释掉。生成编译时错误:“…不包含适合入口点的静态“Main”方法”。这是有意义的,因为程序没有加载,DLL也没有加载

所以问题是,有没有办法做到这一点?我希望DLL中的表单能够确定使用哪个表单启动应用程序:

[STAThread]
static void Main()
{
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);

   if(condition1)
   {
      Application.Run(new Form1());
   }
   else if(condition2)
   {
      Application.Run(new Form2());
   }
}

此逻辑将在多个应用程序中使用,因此将其放在公共组件中是有意义的。

此“静态void Main”方法必须位于“EXE”程序集中,但您可以让此方法调用共享程序集的“Main”版本。您不能直接执行此操作。

将主方法保留在Program.cs中。让它在dll中调用一个方法,该方法根据条件实例化表单并将其返回到Main。

您能在应用程序调用的dll中添加一个静态方法,而不是在Main中进行处理吗

// In DLL
public static class ApplicationStarter
{
     public static void Main()
     {
          // Add logic here.
     }
}

// In program:
{
     [STAThread]
     public static void Main()
     {
          ApplicationStarter.Main();
     }
}
静态void Main()在类库中没有意义,但是,如果将代码片段放在Program.cs中,它应该完全满足您的需要

另外,您是否需要一个catch all'else'子句,以防条件1和条件2不满足?可能不需要,但在大多数情况下,我希望得到某种形式的反馈,而不是应用程序自动退出-当然,这取决于您正在做什么

编辑:如果您只需要将逻辑分离到库中,这可能会满足您的需要

// Program.cs
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    if(MyLib.Condition1)
    {
        Application.Run(new Form1());
    }
    else if(MyLib.Condition2)
    {
        Application.Run(new Form2());
   }
}


// MyLib.cs
...
public static bool Condition1
{
    get
    {
         return resultOfLogicForCondition1;
    }
}
public static bool Condition2
{
    get
    {
         return resultOfLogicForCondition2;
    }
}

实际上,您正在尝试为表单创建一个自定义工厂,以用于应用程序。如下所示:

在EXE中:

static void Main()
{
    Application.Run(new Factory.CreateForm());
}
在你的图书馆里:

public static class Factory 
{
    public static Form CreateForm()
    {
        if( condition ) return new Form1();
        else return new Form2();
    }
}

你当然可以做这种事。我看不出有任何理由从WinForms可执行文件中删除Main()。如何设置条件1、条件2等?发生了什么事情让你说它没有给出预期的结果?