C# 关于CS0433错误的解决方法
C# 关于CS0433错误的解决方法
前言
最近在VS2022中使用.NET6.0开发的时候遇到这样的问题:在调用第三方的dll库文件(FastReport.dll)时,出现CS0433错误(应用程序中引用的两个不同程序集包含相同的命名空间和类型,这会产生歧义。)。
排查
CS0433错误:多个程序集包含相同的类型。当不同的程序集包含相同的类型时,编译器无法确定使用哪个类型,从而导致冲突。
经过排查发现,该库文件中也定义了和系统库或者自己编写的dll库文件中同一个名称的类型,所以造成软件编译报错。
解决
修改.csproj文件,在引入dll文件中添加<Aliases>CustomTypes</Aliases>
修改后,保存重新编译,问题就解决了。
扩展
可参考官方对于CS0433的说明:Compiler Error CS0433 - C# reference | Microsoft Learn
示例
创建了具有模糊类型的第一个副本的DLL
// CS0433_1.cs in CS0433_1.csproj
// or compile with: /target:library
namespace TypeBindConflicts
{ public class AggPubImpAggPubImp { }
}
使用歧义类型的第二个副本创建DLL。
// CS0433_2.cs in CS0433_2.csproj
// or compile with: /target:library
namespace TypeBindConflicts
{ public class AggPubImpAggPubImp { }
}
因此,在项目中使用这两个库(CS0433_1.dll和CS0433_2.dll)时,使用AggPubImpAddPubImp类型会产生歧义,并导致编译器错误CS0433。
<!-- CS0433_3.csproj -->
<ProjectReference Include="..\CS0433_1\CS0433_1.csproj" />
<ProjectReference Include="..\CS0433_2\CS0433_2.csproj" />
// CS0433_3.cs in CS0433_3.csproj
// or compile with: /reference:cs0433_1.dll /reference:cs0433_2.dll
using TypeBindConflicts;public class Test
{ public static void Main(){ AggPubImpAggPubImp n6 = new AggPubImpAggPubImp(); // CS0433 }
}
以下示例显示了如何使用/reference编译器选项的别名功能或<ProjectReference>中的<Aliases>功能来解决此CS0433错误。
<!-- CS0433_4.csproj -->
<ProjectReference Include="..\CS0433_1\CS0433_1.csproj"> <Aliases>CustomTypes</Aliases>
</ProjectReference>
<ProjectReference Include="..\CS0433_2\CS0433_2.csproj" />
// CS0433_4.cs in CS0433_4.csproj
// compile with: /reference:cs0433_1.dll /reference:CustomTypes=cs0433_2.dll
extern alias CustomTypes;
using TypeBindConflicts; public class Test
{ public static void Main(){ // AggPubImpAggPubImp taken from CS0433_1.dll AggPubImpAggPubImp n6 = new AggPubImpAggPubImp();// AggPubImpAggPubImp taken from CS0433_2.dllCustomTypes.TypeBindConflicts.AggPubImpAggPubImp n7 =new CustomTypes.TypeBindConflicts.AggPubImpAggPubImp();}
}