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

.NET 4.7类库转SDK风格后CallerMemberNameAttribute冲突求助

解决.NET 4.7 SDK风格项目中CallerMemberNameAttribute重复定义错误

问题背景

将.NET 4.7传统类库通过Project2015To2017.Migrate2019.Tool转为SDK风格项目后,重建时遇到类型冲突错误:

类型“CallerMemberNameAttribute”同时存在于System.Runtime版本2.6.10.0和mscorlib版本4.0.0.0

代码中使用[CallerMemberName]特性的位置触发该错误,显式引用命名空间无法解决。

可行解决方法

1. 移除不必要的System.Runtime NuGet包

.NET Framework 4.7的mscorlib程序集已经内置了CallerMemberNameAttribute,不需要额外引用System.Runtime NuGet包。直接执行以下命令卸载:

dotnet remove package System.Runtime

之后重新还原包并重建项目即可。

2. 添加程序集绑定重定向

如果必须保留System.Runtime引用,在项目的.csproj中添加自动生成绑定重定向的配置,强制使用mscorlib中的版本:

<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

或者在项目的app.config(类库项目最终需被主应用的配置文件包含)中手动添加绑定重定向:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

3. 使用extern alias区分程序集

若需保留System.Runtime包,可通过别名来指定使用mscorlib中的特性:

  • 编辑.csproj,给System.Runtime包添加别名:
<ItemGroup>
  <PackageReference Include="System.Runtime" Version="4.3.0">
    <Aliases>RuntimeAlias</Aliases>
  </PackageReference>
</ItemGroup>
  • 在代码文件顶部添加extern alias声明:
extern alias RuntimeAlias;
  • 代码中明确指定使用mscorlib的特性:
public void DoSomething([System.Runtime.CompilerServices.CallerMemberName] string nm = "")
{}

4. 确认TargetFramework配置正确性

检查.csproj中的目标框架配置,确保仅设置为.NET 4.7,避免多框架导致的冲突:

<TargetFramework>net47</TargetFramework>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:20:47