1

这是代码:

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]'.
    }
}

为什么我在代码的最后一行得到强制转换异常?

4

2 回答 2

2

您需要声明IC演员interface IC<out T>才能工作。这告诉编译器IC<A>可以分配给类型为 的变量IC<IA>

请参阅此页面以获取说明。

于 2013-02-07T22:52:04.763 回答
1

你可以做

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;
        }
    }
}
于 2013-02-07T22:41:11.190 回答