可能重複:
IList<Type> to IList<BaseType>你爲什麼不能自IList <IParent>轉換爲IList的<IChild>其中ICHILD實現IParent
我在C#中使用.NET 2.0開發,我不明白爲什麼下面的投射結果爲空引用。
如果你有一個IList <ICHILD>,爲什麼你不能把它轉換爲IList <IParent>其中ICHILD實現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);
}
}
}
確切的重複:http://stackoverflow.com/questions/1457265。也可能有用:http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx – 2009-11-10 20:27:40