显式的转换问题(Explicit Casting Problem)

2019-07-18 11:51发布

// The Structure of the Container and the items
public interface IContainer <TItem> where TItem : IItem
{

}

public class AContainer : IContainer<ItemA>
{

}

public interface IItem
{

}

public class ItemA : IItem
{

}

// Client app

[Test]
public void Test ()
{
 IContainer<IItem> container = new AContainer();
}

问:在测试下面的错误occures。 有什么可以用于铸造的解决方案吗?

无法隐式转换类型“的aContainer”到“的IContainer”。 一个显式转换存在(是否缺少强制转换?)

Answer 1:

另一种仿制药协变的问题...

一般类型在.NET不是协变或逆变 - 的IContainer <意达>(其为的aContainer是什么)不是的IContainer <的iItem>的子类 - 有两者之间没有有效的铸造。 这将被固定在C#4。



Answer 2:

如果你想使用AContainer是一个IContainer<IItem>你需要实现这个接口,以及:

public class AContainer : IContainer<ItemA>, IContainer<IItem>

你可以明确地实现它。



Answer 3:

你也可以考虑模拟的协方差由克齐斯茨托夫·克瓦林纳.NET泛型



文章来源: Explicit Casting Problem