編譯器錯誤 CS0034
更新:2007 年 11 月
錯誤訊息
運算子 'operator' 用在型別 'type1' 和 'type2' 的運算元上時其意義會模稜兩可
一個運算子被用在兩個物件上,而編譯器發現一次以上的轉換。由於轉換必須是唯一的,因此您必須進行轉型,或是使其中一個成為明確轉換。如需詳細資訊,請參閱轉換運算子 (C# 程式設計手冊)。
下列範例會產生 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 中,編譯器 Bug 可讓您將具有隱含使用者定義之轉換的類別定義為 int 和 bool,並且在該型別的物件上使用位元 AND 運算子 (&)。在 C# 2.0 中已修正此 Bug,因此編譯器會符合 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;
}
}
}