我的 Monolit .net6 项目中有多个类库。在我的配置文件中,我指定项目应使用哪个库。
通过在我的 API 项目中的 .csproj 中指定条件,我希望添加我将使用的库的引用。因为我不希望不必要的文件出现在我的发布文件中。
我的代码是这样的
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Platforms>AnyCPU;x64</Platforms>
<DefineConstants>PROVINCE_Test1</DefineConstants>
</PropertyGroup>
</ItemGroup>
<ItemGroup Condition="'$(DefineConstants)' == 'PROVINCE_Test1'">
<ProjectReference Include="..\\Test1.csproj" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup Condition="'$(DefineConstants)' == 'PROVINCE_Test2'">
<ProjectReference Include="..\\Test2.csproj" />
</ItemGroup>
</Project>
到目前为止没有问题。 我遇到的问题是在这个program.cs
if (source == "Test1")
{
builder.Services.AddTest1Module();
}
else if (source == "Test2")
{
builder.Services.AddTest2Module();
}
我有这样一个定义。
.AddTest1Module()
和 .AddTest2Module();
的定义会产生错误,因为它们的引用是有条件添加的。找不到相关的库。
我该如何解决这个错误或者我正在尝试做的事情是否正确?
库之间没有关系。它们是两个独立的类库。
我尝试了这段代码,但它无法识别测试
#if PROVINCE_Test1
using Test1;
#endif
最佳答案
问题是这个
<ItemGroup Condition="'$(DefineConstants)' == 'PROVINCE_Test1'">
<ProjectReference Include="..\\Test1.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(DefineConstants)' == 'PROVINCE_Test2'">
<ProjectReference Include="..\\Test2.csproj" />
</ItemGroup>
是一个编译时条件,而这
if (source == "Test1")
{
builder.Services.AddTest1Module();
}
else if (source == "Test2")
{
builder.Services.AddTest2Module();
}
是一个运行时条件。由于编译器无法知道 source
在运行时将具有哪个值,因此 AddTest1Module
和 AddTest2Module
必须在编译时可用。
要解决此问题,您可以在 C# 代码中使用条件编译:
#if PROVINCE_Test1
builder.Services.AddTest1Module();
#endif
#if PROVINCE_Test2
builder.Services.AddTest2Module();
#endif
这也意味着您不再需要保持 .csproj 常量和 source
的值同步:只有前一个是相关的,您不再需要后一个.
关于c# - 条件编译中的引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77613239/