是否正在编译入口程序集的 MSBuild 条件

MSBuild condition for whether the entry assembly is being compiled

我的目标是将另一个 PackageReference 自动添加到任何“入口”程序集。通常它是定义了 Main() 的那个,但没有任何 class 库。

我尝试将类似这样的内容添加到我的 Directory.Build.props:

<Project>
  <ItemGroup Condition=" '$(IS_THE_ENTRY_ASSEMBLY)' == 'true' ">
    <PackageReference Include="Serilog.Sinks.Seq" Version="..." />
  </ItemGroup>
</Project>

我找不到任何 MSBuild 属性 可以告诉我某个程序集是否是入口程序集,因此另一个可行的条件是“此程序集是否引用包 Serilog.Sinks.File?”。为此,我尝试了如下各种形式:

<ItemGroup Condition=" '%(PackageReference.Include)' == 'Serilog.Sinks.File' ">
<ItemGroup Condition=" '%(PackageReference)' == 'Serilog.Sinks.File' ">
<ItemGroup Condition=" '@(PackageReference)' == 'Serilog.Sinks.File' ">

但是,我似乎也找不到执行此操作的正确语法。

欢迎使用任何一种解决方法。

关于如何编译代码有四种可能性:exewinexelibrarymodule(可以在 here 中找到)。通过项目文件中的 <OutputType> 设置。

  • exe 可用于控制台应用程序。可用于 windowed 应用程序,但在启动控制台 window 上打开
  • winexe 可用于 windowed 应用程序。未创建控制台
  • library 用于图书馆。不能直接运行
  • module不知道怎么用

前2个需要Main函数才能运行,所以我们可以检查OutputType是否设置为其中一个

<ItemGroup Condition="'$(OutputType)' == 'exe' or '$(OutputType)' == 'winexe'">
    <!-- only be applied to runnable projects -->
    <ProjectReference Include="...">
</ItemGroup>

如果项目文件中未设置 OutputType - 默认为 Library

不确定字符串比较是区分大小写还是不区分大小写