c# - 为什么不能使用 BindingList<TInherited> 作为采用 BindingList<T> 的方法的参数?

标签 c# .net inheritance ienumerable bindinglist

基本上我有一个具有以下签名的方法:

public void Save(BindingList<T> items);

我正在尝试使用

来调用它
classInstance.Save(items); //items = BindingList<ObjectInheritedFromT>

但 C# 似乎没有意识到继承会引发编译时错误,其中所有代码都是为 T 编写的ObjectInheritedFromT 将完全正常工作也一样,不是吗?

有解决办法吗?我意识到如果是 IEnumerable 就可以了,但后来(奇怪的是)结果是 BindingList<>没有实现 IEnumerable,我需要执行诸如 Remove 之类的操作和Add .

最佳答案

因为BindingList<T>未声明为 BindingList<out T> - 它不支持协方差

读一下:

Covariance and Contravariance FAQ

关于c# - 为什么不能使用 BindingList<TInherited> 作为采用 BindingList<T> 的方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164796/

相关文章:

c# - 在 Entity Framework Core 2.1 中播种关系数据

c# - 如何返回 IAsyncOperation<TReturn> 结果?

c# - P/Invoke & InterOP 中是否有用于编码的匹配类型表?

c# - .NET Core 中的 System.XML 等效函数

c++ - 嵌套类设计 C++ virtual

c# - global.asax 和 global.asax.cs 有什么区别

c# - Entity Framework 4 - 添加自定义字段好吗?

java - 将子类的 ArrayList 复制到父类(super class)的 ArrayList

objective-c - 创建一个 SKSpriteNode 子类的子类

c# - 使用 Youtube API 添加评论在 .NET 中随机失败