'.NET构建'指定主方法

28

我正在使用 dotnet 命令行工具构建一个 .NET Core C# 项目。该项目包含多个带有 main 方法的类,因此我遇到了以下错误:

$ dotnet build
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

Test.cs(18,28): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

Build FAILED.

使用 /main 参数会导致出现错误:

$ dotnet build /main:Test
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

MSBUILD : error MSB1001: Unknown switch.
Switch: /main:Test

我该如何将/main开关传递给dotnet命令?

2个回答

58

您可以编辑您的 csproj 文件来定义要使用哪个类(在 PropertyGroup 内):

<StartupObject>foo.Program2</StartupObject>

或者可以通过在命令行中指定此MSBuild属性来实现:

$ dotnet build foo.csproj -p:StartupObject=foo.Program2

在哪里

namespace foo
{
  class Program2{ public static void Main() {} }
}

3
过去一个小时我尝试了几种方法,直到找到了你的答案。非常感谢你抽出时间记录这个! - koopajah
虽然有点晚了,但在 Web 应用程序中使用这个东西有意义吗?在 VS 2017 中,启动对象设置为项目。我认为这不是标签的有效值。另外,不幸的是,我没有测试项目(现有代码库),因此与应用程序入口点和测试项目入口点相关的答案并不适用。请给予建议。 - EoRaptor013
@EoRaptor013 这个问题涉及到多个类,它们都有 public static Main() 方法,编译器需要在其中选择一个来执行。这与包含多个项目的 sln 文件无关。 - Martin Ullrich
foo是什么,Program2又是什么?它们是命名空间和文件名吗? - Morasiu
3
它想要包含Main方法的类的完整名称(即Namespace.ClassName):在这里,foo将是命名空间,Program2将是类的名称(该文件不一定要叫做Program2.cs)。 - VisualMelon

3
只是补充一下为什么使用/main调用dotnet会导致出错,注意到错误信息中有"Compile with /main"这句话;/main是编译器(csc.exe)的一个参数,而不是dotnet builddotnet build将调用MSBuild.exe,然后再调用csc.exe,但你需要告诉dotnet build哪个类是启动类,以便它可以告诉csc.exe。这就是被接受的答案所做的事情。
或者,如果您直接调用csc.exe,您可以这样传递/main...
csc.exe Program.cs Test.cs /main:TestNamespace.Test

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接