de Possible en double:
IList<Type> to IList<BaseType>Pourquoi ne pouvez-vous jeter de IList <IParent> à IList <IChild> où iChild implémente IParent
Je suis la programmation en C# en utilisant .NET 2.0 et je ne comprends pas pourquoi la distribution ci-dessous entraîne une référence nulle.
Si vous avez un IList <iChild>, pourquoi ne pouvez-vous jeter un IList <IParent> où iChild implémente IParent.
using System.Collections.Generic;
namespace InterfaceTest
{
public interface IParent
{
}
public interface IChild : IParent
{
}
public abstract class Parent : IParent
{
}
public sealed class Child : Parent, IChild
{
}
public sealed class Container
{
public IList<IChild> ChildInterfaceList
{
get;
set;
}
public Container()
{
ChildInterfaceList = new List<IChild>();
}
}
class Program
{
static void Main(string[] args)
{
Container container = new Container();
var childInterfaceList = container.ChildInterfaceList;
System.Diagnostics.Debug.Assert(childInterfaceList != null);
var parentInterfaceList = container.ChildInterfaceList as IList<IParent>;
//I don't expect parentInterfaceList to be null, but it is
System.Diagnostics.Debug.Assert(parentInterfaceList != null);
}
}
}
Exact duplicate: http://stackoverflow.com/questions/1457265. Peut-être aussi utile: http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx –