【问题标题】:Why does MSBuild fails to find my constant in Directory.Build.props?为什么 MSBuild 在 Directory.Build.props 中找不到我的常量?
【发布时间】:2021-01-28 12:00:14
【问题描述】:

我正在尝试使用Directory.Build.props 文件为我的解决方案定义一个简单的预处理器常量。

出于测试目的,我创建了一个控制台应用程序 (C#),并在生成的 .csproj 文件旁边添加了一个 Directoy.Build.props 文件:

<Project>
   <PropertyGroup>
       <DefineConstants>TEST1</DefineConstants>
   </PropertyGroup>
</Project>

我还手动编辑了 .csproj 本身来测试 &lt;DefineConstants&gt; 是否真的有效:

<DefineConstants>DEBUG;TRACE;TEST2;</DefineConstants>

现在是实际代码:

static void Main(string[] args)
{
#if TEST1
    // NOT WORKING!
    Console.WriteLine("<DefineConstants>TEST1</DefineConstants> in Directory.Build.props"); // NOT WORKING!
#else
    Console.WriteLine("failed TEST1 in Directory.Build.props");
#endif

#if TEST2
     // WORKS!
     Console.WriteLine("<DefineConstants>TEST2</DefineConstants> in csproj"); // WORKS!
#else
     Console.WriteLine("failed TEST2 in csproj");
#endif

    }

那么为什么 MSBuild 无法在 Directory.Build.props 中找到我的常量?

【问题讨论】:

  • 看看stackoverflow.com/questions/36793499/…,我猜这同样适用于 Directory.build.props。
  • @Karl-JohanSjögren 哦,哇!做到了!但是有没有办法在不手动编辑 csproj 的情况下自动发生?
  • 使用&lt;DefineConstants&gt;$(DefineConstants), ..&lt;/DefineConstants&gt; 可能会对您有所帮助

标签: c# .net visual-studio msbuild


【解决方案1】:

您应该注意 Directory.Build.props 文件是在 csproj 文件的开头导入的。在你这边,由于导入的属性太早被覆盖,它被 CSProj 中的defineConstants 覆盖。

所以Directory.Build.props 通常用于定义全局属性,而Directory.Build.targets 用于覆盖属性。

Check this link.

所以你应该使用覆盖属性。

解决方案

我有两个解决方案:

1) 将您的 Directory.Build.props 重命名为 Directory.Build.targets 并确保这些在文件中:

<Project>
   <PropertyGroup>
       <DefineConstants>$(DefineConstants)TEST1</DefineConstants>
   </PropertyGroup>
</Project>

确保 csproj 文件是这样的:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE;TEST2;</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>

2) 将文件保留为Directory.Build.props,并将其内容保留为:

<Project>
   <PropertyGroup>
       <DefineConstants>TEST1</DefineConstants>
   </PropertyGroup>
</Project>

将您的 csproj 文件更改为:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE;TEST2;$(DefineConstants)</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>

【讨论】:

  • 谢谢!我最终可能会使用您建议的第一个选项。
猜你喜欢
  • 1970-01-01
  • 2014-04-19
  • 2021-06-12
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
相关资源
最近更新 更多