使用英语阅读

通过


编译器错误 CS0266

无法将类型“type1”隐式转换为“type2”。 存在显式转换(是否缺少强制转换?)

当代码尝试在无法进行隐式转换的两个类型之间转换时,就会发生此错误。 有关详细信息,请参阅显式转换和类型转换

下面的代码演示生成 CS0266 的示例:

C#
// CS0266.cs
class MyClass
{
    public static void Main()
    {
        // You cannot implicitly convert a double to an integer.
        double d = 3.2;

        // The following line causes compiler error CS0266.
        int i1 = d;

        // However, you can resolve the error by using an explicit conversion.
        int i2 = (int)d;  

        // You cannot implicitly convert an object to a class type.
        object obj = new MyClass();

        // The following assignment statement causes error CS0266.
        MyClass myClass = obj;

        // You can resolve the error by using an explicit conversion.
        MyClass c = (MyClass)obj;

        // You cannot implicitly convert a base class object to a derived class type.
        MyClass mc = new MyClass();
        DerivedClass dc = new DerivedClass();

        // The following line causes compiler error CS0266.
        dc = mc;

        // You can resolve the error by using an explicit conversion.
        dc = (DerivedClass)mc;
    }  
}  
  
class DerivedClass : MyClass  
{  
}