You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Framework 4.8引用.NET Standard 2.0程序集引发编译错误

问题分析

你遇到的CS0012错误本质是类型绑定冲突:

  • 在.NET Framework 4.8中,EventLogEntryType默认存在于GAC的System.dll(版本4.0.0.0)中;
  • 你的.NET Standard 2.0库依赖的是NuGet包System.Diagnostics.EventLog 8.0.0中的同名类型,两者属于不同程序集,编译器无法自动匹配;
  • 即使在.NET Framework项目中安装了该NuGet包,编译器仍会优先选择GAC中的System.dll,导致类型不匹配。

另外,你的.NET Standard 2.0库并未直接引用System.Diagnostics.EventLog包,而是通过Microsoft.Extensions.Logging.EventLog间接依赖,这加剧了绑定的不确定性。

解决步骤

1. 修正.NET Standard 2.0库的依赖

在你的.NET Standard库的csproj中,直接添加System.Diagnostics.EventLog的PackageReference,确保依赖明确:

<ItemGroup>
  <!-- 新增直接依赖 -->
  <PackageReference Include="System.Diagnostics.EventLog" Version="8.0.0" />
  <!-- 保留原有其他依赖 -->
  <PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="8.0.0" />
  <!-- ... 其他已有的PackageReference ... -->
</ItemGroup>

重新编译该库,确保输出的程序集明确指向NuGet包中的类型。

2. 为.NET Framework 4.8项目添加程序集绑定重定向

在.NET Framework 4.8项目的App.config或Web.config中,添加绑定重定向规则,强制将System.Diagnostics.EventLog的所有版本定向到8.0.0.0:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.EventLog" 
                          publicKeyToken="cc7b13ffcd2ddd51" 
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" 
                         newVersion="8.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

这会告诉编译器和CLR,无论请求哪个版本的System.Diagnostics.EventLog,都使用8.0.0.0版本。

3. 验证.NET Framework项目的引用

  • 确保.NET Framework项目中已安装System.Diagnostics.EventLog 8.0.0 NuGet包;
  • 检查项目引用中是否存在System.Diagnostics.EventLog(来自NuGet包,而非GAC的System.dll);
  • 清理项目的bin/obj目录,重新编译,避免旧的程序集缓存干扰。

备选方案:封装类型避免直接暴露

如果上述方法仍有问题,可以在.NET Standard库中封装EventLogEntryType,避免直接将外部类型暴露给调用方:

// 在.NET Standard库中定义自己的枚举
public enum CustomEventLogEntryType
{
    Error = EventLogEntryType.Error,
    Warning = EventLogEntryType.Warning,
    Information = EventLogEntryType.Information
}

// 修改WriteEventLog方法
public static void WriteEventLog(string Source, string Message, CustomEventLogEntryType EvType)
{
    EventLogEntryType originalType = (EventLogEntryType)EvType;
    // 原有逻辑...
}

这样调用方(.NET Framework项目)只需要引用你的库,无需处理外部类型的绑定冲突。

内容的提问来源于stack exchange,提问作者Saftpresse99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:20:22