简体   繁体   中英

Implicit cast on reference type

I have the following code with the explicit cast a = (Class2)o

using System;

class Class1 { }
class Class2 : Class1{ }

class IsTest
{
    static void Test(object o)
    {
        Class1 a;
        Class2 b;

        if (o is Class2)
        {
            Console.WriteLine("o is Class2");
            a = (Class2)o; // Works
            a = o; // **implicit cast won't work - error CS0266**
        }
    }
    static void Main()
    {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();        
        Test(c2);
    }
}

When I'm trying to implicit cast a = o it gives me the error CS0266. From what I know converting a reference type to a direct or indirect ancestor class is a widening conversion, so a program can make the conversion implicitly.

b is derived from a, so why the implicit cast doesn't work?

It is as per the C# standard:

Thus, conversion operators are not allowed to convert from or to object because implicit and explicit conversions already exist between object and all other types.

https://msdn.microsoft.com/en-us/library/aa664464(v=vs.71).aspx

Additionally to that see all the possible implicit conversions defined in 13.1.4 Implicit reference conversions at the http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

I would like to answer this with an example.

double d = 1.35456;
int i = d;

This code will throw the same error CS0266.

Why?

In my opinion, because there is a possibility of loss of information when converting a bigger type to a smaller type, language wants to make sure that you are intentionally converting the types by forcing you to use explicit conversion.

Your case is similar where you are trying to convert an object type to Class C2 type. This Object O could be pointing to any Class type. For example, you may consider the below code where a new class C3 is introduced which is derived from C2 and has an extra property.

using System;

class Class1 { }
class Class2 : Class1{ }
class Class3: Class2{ public  string S{get; set;} }

public class IsTest
{
     static void Test(object o)
    {
        Class1 a;
        Class2 b;

           if (o is Class2)
        {
            Console.WriteLine("o is Class2");
            a = (Class2)o;
        }


    }
    public static void Main()
    {
        Class1 c1 = new Class1();
        Class3 c3 = new Class3(){ S = "This is Lost"};
        Test(c3);

    }
}

When casting in the way you specified, we lose this property and hence the language is forcing you to make it an explicit casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM