将Collection <T>转换为接口 - 为什么它不起作用?

jos*_*ley 1 c# collections casting

有人可以解释为什么下面的代码抛出以下异常:

InvalidCastException: Unable to cast object of type 'System.Collections.ObjectModel.Collection'1[UserQuery+Test]' to type 'System.Collections.ObjectModel.Collection'1[UserQuery+ITest]'.

public interface ITest
{
}

public class Test : ITest
{
}

void Main()
{
  Collection<Test> t = new Collection<Test>();
  t.Add(new UserQuery.Test());
  var casted = (Collection<ITest>)t.Cast<ITest>();
}
Run Code Online (Sandbox Code Playgroud)

Cast<T>隐含的签名T是输出,但事实并非如此.到底是怎么回事?和它covariance有什么关系吗?

Ree*_*sey 6

当你使用时Enumerable.Cast<T>,你正在创造一种新的IEnumerable<T>,而不仅仅是传统意义上的"演员".

因此,返回的集合不再是Collection<T>,而是内部(非公共)实现IEnumerable<ITest>.