次のタイプが与えられます:
public interface IPrimary{ void doBattle(); }
// an ISecondary "is" an IPrimary
public interface ISecondary : IPrimary { }
// An implementation of ISecondary is also an IPrimary:
internal class SecondaryImpl : ISecondary
{
// Required, since this is an IPrimary
public void doBattle(){ }
}
なぜ私はこれを行うことができないのですか?
List<IPrimary> list = new List<ISecondary>();
これにより、次のコンパイルエラーが発生します。
引数タイプ'System.Collections.Generic.List'はパラメータータイプ'System.Collections.Generic.List'に割り当てることができません
エラーを理解し、回避策があることを認識しています。この直接変換が許可されない明確な理由はわかりません。のリストに含まれる値は、結局のところISecondary
、タイプの値であるIPrimary
必要がList<IPrimary>
ありList<ISecondary>
ます。なぜ、無関係のタイプとして解釈されるのでしょうか。
C#がこのように設計されている理由を誰かが明確に説明できますか?
少し拡張された例:次のようなことをしようとしたときに問題が発生しました。
internal class Program
{
private static void Main(string[] args)
{
// Instance of ISecondary, and by extention, IPrimary:
var mySecondaryInstance = new SecondaryImpl();
// This works as expected:
AcceptImpl(mySecondaryInstance);
// List of instances of ISecondary, which are also,
// by extention, instances of IPrimary:
var myListOfSecondaries = new List<ISecondary> {mySecondaryInstance};
// This, however, does not work (results in a compilation error):
AcceptList(myListOfSecondaries);
}
// Note: IPrimary parameter:
public static void AcceptImpl(IPrimary instance){ }
// Note: List of type IPrimary:
public static void AcceptList(List<IPrimary> list){ }
}