您不能将一种类型的 List 强制转换为另一种类型的 List。
如果你仔细想想,你会很高兴你做不到。想象一下,如果可能的话,你可能造成的破坏:
interface ICustomRequired
{
}
class ImplementationOne : ICustomRequired
{
}
class ImplementationTwo: ICustomRequired
{
}
var listOne = new List<ImplementationOne>();
var castReference = listOne as List<ICustomRequired>();
// Because you did a cast, the two instances would point
// to the same in-memory object
// Now I can do this....
castReference.Add(new ImplementationTwo());
// listOne was constructed as a list of ImplementationOne objects,
// but I just managed to insert an object of a different type
但是请注意,这行代码是合法的:
exampleList as IEnumerable<ICustomRequired>;
这将是安全的,因为IEnumerable 不会为您提供任何添加新对象的方法。
IEnumerable<T>实际上定义为IEnumerable<out t>,也就是说类型参数是Covariant。
你能把函数的参数改成IEnumerable<ICustomRequired>吗?
否则,您唯一的选择就是创建一个新列表。
var newList = (exampleList as IEnumerable<ICustomRequired>).ToList();
或
var newList = exampleList.Cast<ICustomRequired>().ToList();