c# - Action<List<Something>> 逆变限制

标签 c# list action contravariance

我正在编写一个网络应用程序,其中对象通过 id 请求并通过委托(delegate)回调返回:

public static void requestById<ModelType>(T id, Action<ModelType> callback)
    where ModelType : AbstractModel<T>
{
}

为了方便起见,我有一种一次请求多个对象的方法:

public static void requestByIds<ModelType>
    (List<T> ids, Action<List<ModelType>> callback)
    where ModelType : AbstractModel<T>, new()
{
}

接下来,我有一个具有多个子项的抽象模型对象,以及一个用于请求其子项的方法:

public abstract void requestSections(Action<List<AbstractSection>> callback);

然后在具体类中实现:

public override void requestSections(Action<List<AbstractSection>> callback)
{
    Section.requestByIds<Section>(this.sectionIds, callback);
}

突然我找到了代表

Action<List<AbstractSection>>

不兼容

Action<List<Section>>

这是 C# 中逆变的限制吗?有什么解决方法可以让我的覆盖方法起作用吗?谢谢

最佳答案

List是不变的,它不是协变或逆变的。

如果您使用 IEnumerable<T>而不是列表,您可以信赖 IEnumerable<T>T 协变,这使得 Action<IEnumerable<T>>相对于 T 逆变.

关于c# - Action<List<Something>> 逆变限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551150/

相关文章:

html - 在客户结帐时更改颜色并禁用温度的按钮

Java swing 键绑定(bind)

c# - 将 Logo 添加到 Orchard 主题的页面

c# - 从 try...catch 返回 null 的方法

c# - Silverlight DataGrid 中的多行单元格

c# - 更改项目在 List<string> 中的位置

python - 在Python中比较两个列表的子列表

python - 如何查找列表中嵌套列表的数量?

wordpress - 页脚中的 wp_enqueue_script

c# - 与数据库无关的 ASP.Net?