为什么我在这里得到Unable to cast异常

本文关键字:to cast 异常 Unable 在这里 为什么 | 更新日期: 2023-09-27 17:58:19

以下是代码:

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

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

为什么我在这里得到Unable to cast异常

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

有关说明,请参阅本页。

您可以进行

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;
        }
    }
}