TypeName1 的類型同時存在於 TypeName2 和 TypeName3 中
應用程式中參考的兩個不同的元件包含相同的命名空間和類型,這會產生模棱兩可。
若要解決此錯誤,請使用 extern alias 功能搭配專案引用別名,或不要引用其中一個程序集。 您也可以在直接使用 C# 編譯器進行編譯時,使用 [參考] 編譯器選項中的別名功能。
如果下列情況,也可能會發生此錯誤:
- 指令
@ Page在應該是CodeFile屬性時具有CodeBehind屬性。 - 程序代碼會放在不應該位於 該處的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();
}
}