为什么强制转换为ICollection <ifoo>返回null,其中强制转换为ICollection <foo>并不是什么?

时间:2017-06-14 09:03:14

标签: c# interface casting

在下面的示例中,函数ICollection<Foo> Cast(List<Foo> stuff)不返回null:

public class Foo
{
    public string test { get; set; }
}

[TestClass]
public class Test
{
    private List<Foo> Foos = new List<Foo>();

    private ICollection<Foo> Cast(List<Foo> stuff)
    {
        return stuff as ICollection<Foo>;
    }

    [TestMethod]
    public void TestCast()
    {
        ICollection<Foo> stuff = Cast(Foos);
        Assert.IsTrue(stuff != null);
    }
}

但是在下一个例子中,它确实返回null。为什么是这样?

public interface IFoo { }

public class Foo : IFoo
{
    public string test { get; set; }
}

[TestClass]
public class Test
{
    private List<Foo> Foos = new List<Foo>();

    private ICollection<IFoo> Cast(List<Foo> stuff)
    {
        return stuff as ICollection<IFoo>;
    }

    [TestMethod]
    public void TestCast()
    {
        ICollection<IFoo> stuff = Cast(Foos);
        Assert.IsTrue(stuff != null);
    }
}

0 个答案:

没有答案