为什么我在这里收到无法投射异常 [英] Why I am getting the Unable to cast exception here

查看:58
本文介绍了为什么我在这里收到无法投射异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

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 ?

推荐答案

您需要将 IC 声明为 interface IC 才能使演员表工作.这告诉编译器 IC 可以分配给 IC 类型的变量.

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>.

请参阅此页面了解说明.

这篇关于为什么我在这里收到无法投射异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆