c# - 条件编译中的引用错误

标签 c# .net

我的 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 在运行时将具有哪个值,因此 AddTest1ModuleAddTest2Module 必须在编译时可用。

要解决此问题,您可以在 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/

相关文章:

.net - 如何修改 .net 的 BackgroundWorker 类,以便它在方法完成时触发自定义事件

c# - 使用 PST/CEST/UTC/等形式的时区解析 DateTime

C#错误与ExcelDataReader

c# - 有没有办法在执行代码时获取当前行号? C#

c# - MVC 5 C#将错误报告回数据库

c# - 复杂模型+集合+IFormFile的REST API模型绑定(bind)

c# - 在 C# 中生成异步方法调用 - AOP?

c# - 在 Linq 中处理临时计算

c# - 在进程加载后完成操作

c# - 矩阵和向量的点积