Explicit Casting Problem

后端 未结 3 1692
轻奢々
轻奢々 2020-12-04 04:22
// The Structure of the Container and the items
public interface IContainer  where TItem : IItem
{

}

public class AContainer : IContainer         


        
相关标签:
3条回答
  • 2020-12-04 04:50

    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.

    0 讨论(0)
  • 2020-12-04 04:55

    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.

    0 讨论(0)
  • 2020-12-04 05:02

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

    0 讨论(0)
提交回复
热议问题