如果我有
<ProjectReference>
引用,有什么方法可以将条件编译值传递给该项目吗?像这样的东西(我知道<DefineConstants>
不存在这样的,这只是为了说明需要):
<ProjectReference Include="..\DataProducer\DataProducer.csproj">
<DefineConstants>WAS_SET</DefineConstants>
<ProjectReference>
因此,如果该项目中有一个这样的类:
public sealed class ProduceValue
{
public string Produce()
{
#if WAS_SET
return "WAS SET";
#else
return "NOTHING WAS SET";
#endif
}
}
然后通过在编译期间传递该值或不传递该值,我可以获得不同的输出。
ProjectReference
项允许添加元数据字段 Properties
和 UndefineProperties
,以允许操作用于构建项目引用的“全局”属性集。您可以通过将全局属性传递给引用的项目来利用它,如下所示:
<ProjectReference Include="..\DataProducer\DataProducer.csproj">
<Properties>DefineConstants=WAS_SET</Properties>
</ProjectReference>
现在成为引用项目的全局属性的效果是,它将覆盖项目中静态定义的
DefineConstants
的任何定义/更新 - 这还可能包括任何添加的配置常量 (DEBUG
)。
如果常量由启动项目确定,那么您可以为项目创建新配置并将常量添加到这些新配置中。
然后,在你的 DataProducer.csproj 中你可以有这样的东西
<PropertyGroup>
<Configurations>Debug;Release;DebugMYCONSTANTS</Configurations>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugMYCONSTANTS|AnyCPU'">
<DefineConstants>$(DefineConstants);WAS_SET</DefineConstants>
</PropertyGroup>
此后,您只需使用 DebugMYCONSTANTS 配置启动项目即可。
或者,您可以只检查配置而不是常量
public sealed class ProduceValue
{
public string Produce()
{
#if DebugMYCONSTANTS
return "WAS SET";
#else
return "NOTHING WAS SET";
#endif
}
}
我也有类似的问题。
里面有 2 个具有相同类型的项目(我们称它们为 CommonTypes1 和 CommonTypes2)。
此外,还有另一个项目(让我们将其命名为Models),它必须根据某些条件依赖于 CommonTypes1 或 CommonTypes2。 然后我想要:
我尝试了与项目引用、属性、配置、msbuild 任务等相关的不同方法。 但通过创建添加 Models2 项目解决了问题,但我没有复制所有 cs 文件,而是使用了以下链接:
in Models2.csproject:
<Compile
Include="..\Models\**\*.cs"
Exclude="..\Models\bin\**\*.*;..\Models\obj\**\*.*">
</Compile>
查看更多详情这里
我认为可能的解决方案是“ProjectReference”的“Targets” https://github.com/dotnet/msbuild/blob/master/src/MSBuild/MSBuild/Microsoft.Build.CommonTypes.xsd#L644
在 DataProducer.csproj 中定义目标。 在目标中定义 Constants 属性。 因此在构建目标之前先创建目标。
那么它应该可以工作吗?
更新:
尝试了我的上一个选项,它不起作用。 另一种选择:
因此 DataProducer.csproj 和 DataProducer.WAS_SET.csproj 将共享代码。 我们可以参考任何我们想要的。
我们可以为这两个 csproj 使用不同的 AssemblyName。 因此相同的源代码,但不同的 dll。