Explicit Casting Problem

落花浮王杯 提交于 2019-11-26 18:40:03

问题


// 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?

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


回答1:


Another generics covariant problem...

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.




回答2:


If you want to use AContainer to be an IContainer<IItem>, you need to implement this interface as well:

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

You may implement it explicitly.




回答3:


You can also consider Simulated Covariance for .NET Generics by Krzysztof Cwalina



来源:https://stackoverflow.com/questions/1443341/explicit-casting-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!