質問
// 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();
}
質問:テストでは、次のエラーが発生します。キャストの解決策は何ですか?
タイプ「AContainer」を「IContainer」に暗黙的に変換することはできません。明示的な変換が存在します(キャストを見逃していますか?)
解決
別のジェネリック共変問題...
.NETのジェネリック型は共変でも反変でもありません-IContainer <!> lt; ItemA <!> gt; (これがAContainerである)は、IContainer <!> lt; IItem <!> gt;のサブクラスではありません。 -2つの間に有効なキャストはありません。これはC#4で修正されます。
他のヒント
AContainer
を使用してIContainer<IItem>
にしたい場合は、このインターフェースも実装する必要があります:
public class AContainer : IContainer<ItemA>, IContainer<IItem>
明示的に実装できます。
所属していません StackOverflow