类型 TypeName1 同时存在于 TypeName2 和 TypeName3 中
应用程序中引用的两个不同的程序集包含相同的命名空间和类型,这会产生歧义。
若要解决此错误,请将 extern alias 该功能与项目引用别名一起使用,或者不引用其中一个程序集。 还可以在直接使用 C# 编译器编译时使用 (References) 编译器选项的别名功能。
如果出现以下情况,也可能发生此错误:
- 当此指令应使用
CodeBehind属性时,@ Page指令具有CodeFile属性。 - 代码放置在不应驻留在 App_Code 文件夹中。
如何标识冲突的程序集
完整的错误消息显示哪些程序集包含冲突类型。 消息格式为:
error CS0433: The type 'N.C' exists in both 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
在此示例中,冲突的程序集为 A 和 B。程序集名称显示在版本信息之前的单引号中。 使用这些程序集名称来确定导致冲突的引用,并决定如何解决它。
例子
此代码创建包含不明确类型第一个副本的 DLL。
// CS0433_1.cs in CS0433_1.csproj
// compile with: dotnet build or /target:library
namespace TypeBindConflicts
{
public class AggPubImpAggPubImp { }
}
此代码用歧义类型的第二个副本创建 DLL。
// CS0433_2.cs in CS0433_2.csproj
// compile with: dotnet build or /target:library
namespace TypeBindConflicts
{
public class AggPubImpAggPubImp { }
}
因此,在项目中使用这两个库(CS0433_1.dll 和 CS0433_2.dll)时,使用 AggPubImpAggPubImp 类型将不明确,并将导致编译器错误 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
// compile with: dotnet build or /reference:cs0433_1.dll /reference:cs0433_2.dll
using TypeBindConflicts;
public class Test
{
public static void Main()
{
AggPubImpAggPubImp n6 = new AggPubImpAggPubImp(); // CS0433
}
}
以下示例演示如何将 extern alias 该功能与项目引用配合使用来解决此 CS0433 错误。 这是新式 .NET 项目的建议方法。
步骤 1:向其中一个项目引用添加别名
首先,修改项目文件,将别名添加到冲突的项目引用之一:
<!-- CS0433_4.csproj -->
<ProjectReference Include="..\CS0433_1\CS0433_1.csproj">
<Aliases>CustomTypes</Aliases>
</ProjectReference>
<ProjectReference Include="..\CS0433_2\CS0433_2.csproj" />
步骤 2:在代码中使用 extern 别名
然后,使用 extern alias 指令和限定的类型名称来区分这两种类型:
// CS0433_4.cs in CS0433_4.csproj
// compile with: dotnet build or /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_2.dll (no alias, default global namespace)
AggPubImpAggPubImp n6 = new AggPubImpAggPubImp();
// AggPubImpAggPubImp taken from CS0433_1.dll (via CustomTypes alias)
CustomTypes.TypeBindConflicts.AggPubImpAggPubImp n7 =
new CustomTypes.TypeBindConflicts.AggPubImpAggPubImp();
}
}