以下是代码:
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]'.
}
}
为什么我在代码的最后一行得到了转换异常?
答案 0 :(得分:2)
您需要将IC
声明为interface IC<out T>
才能使投射有效。这告诉编译器可以将IC<A>
分配给IC<IA>
类型的变量。
请参阅this page获取解释。
答案 1 :(得分: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;
}
}
}