显式转换问题 [英] Explicit Casting Problem

查看:23
本文介绍了显式转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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();
}

问题:在测试中出现以下错误.铸造的解决方案是什么?

Question : In test the following error occures. What can be the solution for casting?

无法将类型AContainer"隐式转换为IContainer".存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'AContainer' to 'IContainer'. An explicit conversion exists (are you missing a cast?)

推荐答案

另一个泛型协变问题...

Another generics covariant problem...

.NET 中的泛型类型不是协变或逆变的 - IContainer(这就是 AContainer)不是 IContainer<IItem> 的子类.- 两者之间没有有效的演员阵容.这将在 C# 4 中修复.

Generic types in .NET are not covariant or contravariant - IContainer<ItemA> (which is what AContainer is) is not a subclass of IContainer<IItem> - there is no valid cast between the two. This will be fixed in C# 4.

这篇关于显式转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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