简体   繁体   中英

Why I am getting the Unable to cast exception here

Here is the code:

interface IA
{
}

interface IC<T>
{
}

class A : IA
{
}

class CA : IC<A>
{
}

class Program
{
    static void Main(string[] args)
    {
        IA a;
        a = (IA)new A();    // <~~~ No exception here

        IC<IA> ica;

        ica = (IC<IA>)(new CA()); // <~~~ Runtime exception: Unable to cast object of type 'MyApp.CA' to type 'MyApp.IC`1[MyApp.IA]'.
    }
}

Why am I getting the casting exception in the last line of the code ?

You need to declare IC as interface IC<out T> for the cast to work. This tells the compiler that IC<A> can be assigned to a variable of type IC<IA> .

See, this page for an explanation.

you can do

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    interface IPerson
    {
    }

    //Have to declare T as out
    interface ICrazy<out T>
    {
    }

    class GTFan : IPerson
    {
    }

    class CrazyOldDude : ICrazy<GTFan>
    {
    }

    class Program
    {
        static void Main(string[] args) {
            IPerson someone;
            someone = (IPerson)new GTFan();    // <~~~ No exception here

            ICrazy<GTFan> crazyGTFanatic;
            ICrazy<IPerson> crazyPerson;

            crazyGTFanatic = new CrazyOldDude() as ICrazy<GTFan>;

            crazyGTFanatic = (ICrazy<GTFan>)(new CrazyOldDude());

            crazyPerson = (ICrazy<IPerson>)crazyGTFanatic;
        }
    }
}

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