【发布时间】:2009-11-10 20:23:25
【问题描述】:
我正在使用 .NET 2.0 在 C# 中编程,但我不明白为什么下面的强制转换会导致空引用。
如果你有一个 IList
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);
}
}
}
【问题讨论】:
标签: c# generics inheritance list interface