ILRepack打包netstandard2.0项目引入Newtonsoft.Json报NullableAttribute错误
ILRepack合并Newtonsoft.Json时NullableAttribute冲突解决方案
根因说明
- 报错的核心是两个不同模块存在同名的
System.Runtime.CompilerServices.NullableAttribute定义:- 一份是你手动在主项目中定义的
- 另一份是Newtonsoft.Json 13.x为了兼容低版本框架,内嵌在自身程序集中的internal级同名Attribute
- 你在ILRepack配置中将Newtonsoft.Json加入了
DoNotInternalizeAssemblies列表,ILRepack不会修改Newtonsoft.Json内部的类型引用,Mono.Cecil按「类型名+所属程序集」的规则判断类型唯一性,不会将两份同名Attribute识别为同一个类型,因此抛出需要导入外部模块成员的错误,这也是你手动定义的Attribute无法生效的核心原因。 - Debug模式不会触发ILRepack执行,编译阶段只要能找到NullableAttribute定义就不会报错,和合并阶段的错误无关联。
可行解决方案
按优先级排序:
- 方案1:禁用项目可空注解,删除手动定义的Attribute
在项目.csproj的<PropertyGroup>节点中添加配置:
同时删除你手动编写的NullableAttribute类。该配置会让你的项目完全不生成可空相关的Attribute标记,合并时只会处理Newtonsoft.Json内部的可空Attribute,不会出现类型冲突。<Nullable>disable</Nullable> - 方案2:配置ILRepack过滤可空Attribute
在你的ILRepack节点中添加CustomAttributeBlacklist参数,指定过滤NullableAttribute:
ILRepack合并时会自动删除所有程序集中的该Attribute引用,直接绕过类型冲突问题,不会影响业务逻辑运行。<ILRepack Parallel="true" DebugInfo="true" Verbose="true" Internalize="true" InternalizeExclude="@(DoNotInternalizeAssemblies)" Wildcards="true" InputAssemblies="@(InputAssemblies)" LibraryPath="@(LibraryPath)" KeyFile="$(AssemblyOriginatorKeyFile)" TargetKind="SameAsPrimaryAssembly" OutputFile="$(OutputPath)$(AssemblyName)$(TargetExt)" LogFile="output.txt" CustomAttributeBlacklist="System.Runtime.CompilerServices.NullableAttribute" /> - 方案3:调整Newtonsoft.Json的内部化配置
如果你没有强需求必须保留Newtonsoft.Json不被内部化,可以将它从DoNotInternalizeAssemblies列表中移除,ILRepack会将Newtonsoft.Json的所有类型合并到主程序集,统一处理Attribute引用,也能解决冲突。
内容的提问来源于stack exchange,提问作者Capsup
相关产品推荐
相关产品推荐

