【发布时间】:2017-12-21 16:33:25
【问题描述】:
考虑以下代码:
public class Thing : IThing { }
public interface IThing {}
public interface IContainer<out T> where T : IThing { }
// This works
// public class Container<T> : IContainer<T> where T : IThing { }
// This doesn't work
public class Container<T> : IContainer<IThing> where T : IThing {}
internal class Program
{
private static void Main(string[] args)
{
var concreteContainer = new Container<Thing>();
var abstractContainer = (IContainer<Thing>) concreteContainer;
}
}
在这一行:
var abstractContainer = (IContainer<Thing>) concreteContainer;
您会收到以下运行时错误:
InvalidCastException: Unable to cast object of type 'CastTest.Container`1[CastTest.Thing]' to type CastTest.IContainer`1[CastTest.Thing]'.
另外,如果你有 Resharper,它会抱怨 Suspecious cast: there is no type in the solution which is inherited from both 'Container<Thing>' and 'IContainer<Thing>'。
为什么需要一个从两者都继承的类型? Container<T> 没有实现IContainer<IThing> 吗?由于Thing 实现了IThing,并且Container<T> 中的T 保证实现IThing,看来我应该能够执行此转换。
【问题讨论】:
-
Container<Thing>实现IContainer<IThing>而不是IContainer<Thing>。 -
@hvd 什么,现在你要我真正注意?!天啊,人们问了很多。哎呀!
标签: c# generics interface casting