Compiler Error CS0173

无法确定条件表达式的类型,因为“class1”和“class2”之间没有隐式转换

当希望不同类的对象在同一代码中使用时,类之间的转换非常有用。然而,在一起工作的两个类不能有相互转换和多余转换,也不能有隐式转换。 class1class2 的类型分别确定,选择更全面的类型作为条件表达式的类型。有关类型的确定方式的更多信息,请参见Conditional operator cannot cast implicitly

若要解决 CS0173,请确认 class1class2 之间有且仅有一个隐式转换,而不论向哪个方向进行转换或在哪个类中进行转换。有关更多信息,请参见隐式数值转换表(C# 参考)转换运算符(C# 编程指南)

下面的示例生成 CS0173:

// CS0173.cs
public class C {}

public class A 
{
    //// The following code defines an implicit conversion operator from  
    //// type C to type A.
    //public static implicit operator A(C c)
    //{
    //    A a = new A();
    //    a = c;
    //    return a;
    //}
}

public class MyClass
{
    public static void F(bool b)
    {
        A a = new A();
        C c = new C();

        // The following line causes CS0173 because there is no implicit
        // conversion from a to c or from c to a.
        object o = b ? a : c;

        // To resolve the error, you can cast a and c.
        //object o = b ? (object)a : (object)c;

        // Alternatively, you can add a conversion operator from class C to
        // class A, or from class A to class C, but not both.
    }

   public static void Main()
   {
      F(true);
   }
}

下面的代码在 Visual Studio 2005 中不生成 CS0173,但在更高版本中会生成 CS0173。

//cs0173_2.cs
class M
{
    static int Main ()
    {
        int X = 1;
        // The following line causes CS0173 in Visual Studio 2005.
        object o = (X == 0) ? null : null;
        return -1;
    }
}