显式铸造问题 [英] Explicit Casting Problem

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

问题描述

// 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< ItemA> (这是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天全站免登陆