如何在 dot net core 中设置默认文件(起点)

How to set the default file(starting point) in dot net core

我正在尝试探索 dot net 核心功能以更好地理解它,因为我执行了同样的操作

dotnet new
dotnet build
dotnet run

命令提示符 window 中的命令,它为我创建了一个项目并创建了名称为 Project.cs 的文件,最后它在 window 中显示了 Hello World! .

现在我在同一文件夹结构中添加了一个不同名称的文件 SampleDotNetCoreApp.cs,我想知道如何将 SampleDotNetCoreApp.cs 设置为程序执行的默认起点执行 dotnet run 命令。

换句话说,当我在同一文件夹中有多个 cs 文件时,我想知道如何更改 dot net core 中的起始执行点。

添加

"entryPoint": "ADifferentMethod"

在 project.json 的顶层。

详情请参考https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json#entrypoint

程序的入口点由静态Main 方法定义。

当执行 dotnet new 时,这将创建 Program.cs 并在其中使用此方法:

public static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
}

这成为程序的入口点(因为它是项目中唯一的 static Main 方法。

要从命令行使用 static Main 方法添加新的 .cs 文件,您可以使用:

echo using System;namespace ConsoleApplication{public class SampleDotNetCoreApp{public static void Main(string[] args){Console.WriteLine("Hello NEW World!");}}} > SampleDotNetCoreApp.cs

但是,如果您现在 运行 dotnet build 您将收到此错误:

Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

因为有2个static Main方法。我无法弄清楚 Compile with /main 的含义,但要克服此错误,您可以 运行 一个与上述类似的 echo 命令,但这次更改 Program.cs :

echo using System;namespace ConsoleApplication{public class Program{public static void MainOLD(string[] args){Console.WriteLine("Hello World!");}}} > Program.cs

现在你只有 1 个 static Main,你可以 运行

dotnet build
dotnet run

并查看输出:

Hello NEW World!

这几乎肯定不是推荐的做法,但希望它能给你一些想法。

解决此问题的正确方法 - 在不删除代码的情况下确保您只有一个主要方法,并且至少给出:

.NET Command Line Tools (1.1.6)

Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core

是使用以下参数调用构建:

dotnet build /property:StartupObject=namespace.ClassWithMain

错误消息将您指向根本不受支持的 /main,这非常令人困惑 - 我最终找到了正确的 属性 使用(注意,我曾使用 /属性:main 或 /属性:Main 无济于事)来自这里的答案:

希望对您有所帮助

您可以编辑 "Project.csproj" 文件以指定使用哪种 Main 方法

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <StartupObject>Project.SampleDotNetCoreApp</StartupObject>
</PropertyGroup>

注意 StartupObject 标签,识别 class 来启动程序。这个 class 必须有一个 static Main(string[] args) 方法。

使用dotnet restore确保更改成功保存,然后构建/运行项目

dotnet run and dotnet build do perform an automatic restore, so doing this manually is not necessary

- 是的,我知道我迟到了,但我刚遇到这个问题,发现很难解决。不妨分享一下我新发现的智慧。