コンパイラ エラー CS0034
型 'type1' および 'type2' のオペランドの演算子 'operator' があいまいです
1 つの演算子が 2 つのオブジェクトに使用され、複数の変換が見つかりました。 変換は一意である必要があるため、キャストを行うか、いずれかの変換を明示的にする必要があります。 詳細については、「ユーザー定義の変換演算子」 に関するページを参照してください。
次の例では CS0034 が生成されます。
// CS0034.cs
public class A
{
// Allows for the conversion of A object to int.
public static implicit operator int (A s)
{
return 0;
}
public static implicit operator string (A i)
{
return null;
}
}
public class B
{
public static implicit operator int (B s)
// One way to resolve this CS0034 is to make one conversion explicit.
// public static explicit operator int (B s)
{
return 0;
}
public static implicit operator string (B i)
{
return null;
}
public static implicit operator B (string i)
{
return null;
}
public static implicit operator B (int i)
{
return null;
}
}
public class C
{
public static void Main()
{
A a = new A();
B b = new B();
b = b + a; // CS0034
// Another way to resolve this CS0034 is to make a cast.
// b = b + (int)a;
}
}
C# 1.1 では、コンパイラのバグによって、int
および bool
の両方への暗黙的なユーザー定義変換を含むクラスが定義され、その型のオブジェクトに対してビットごとの AND
演算子 (&
) が使用される可能性があります。 C# 2.0 では、このバグは修正され、コンパイラは C# 仕様に準拠するようになったため、次のコードで CS0034 が発生するようになります。
namespace CS0034
{
class TestClass2
{
public void Test()
{
TestClass o1 = new TestClass();
TestClass o2 = new TestClass();
TestClass o3 = o1 & o2; //CS0034
}
}
class TestClass
{
public static implicit operator int(TestClass o)
{
return 1;
}
public static implicit operator TestClass(int v)
{
return new TestClass();
}
public static implicit operator bool(TestClass o)
{
return true;
}
}
}
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示