【问题标题】:C# equivalent of <? extends Type>? [closed]C# 等价于 <?扩展类型>? [关闭]
【发布时间】:2019-02-01 09:28:01
【问题描述】:

我正在使用 C#。我在我的代码中创建了一个名为 EntityInterface 的接口。我写了这个函数:

private void Save(List<EntityInterface> entities)
{ ... }

在我的代码的其他地方,我有一个变量,定义为List&lt;Job&gt;。 Job 类是一个实现 EntityInterface 的类。

我无法将我的 Job 对象列表传递给 Save 方法。编译器报错参数类型错误,因为List&lt;Job&gt;List&lt;EntityInterface&gt;不一样。

我需要修改函数以表达参数可以是“实现 EntityInterface 的任何对象的列表”的想法。我已经四处搜索,但找不到如何执行此操作的示例。

【问题讨论】:

  • 您在寻找generics吗?还是generic constraints?
  • 请粘贴您要传递的定义,以及您的方法的实际类型。
  • 不完全确定你在问什么(因为&lt;? extends Type &gt;? 不是 C# 概念),但你应该重新阅读为什么你不能convert list of derived type to list of base type 因为你可能错过了那里的一些信息。跨度>
  • 试试private void Save&lt;T&gt;(List&lt;T&gt; entities) where T : EntityInterface
  • 你说的是协方差,但我同意@enigmativity

标签: c# generics


【解决方案1】:

你的模型应该是这样的:

using System.Collections.Generic;

public interface IEntity
{
    void Save<T>(List<T> entities) where T : IEntity;
}

public class Job : IEntity
{
    void IEntity.Save<T>(List<T> entities) { }
}

public class TargetImpl : IEntity
{
    void IEntity.Save<T>(List<T> entities) { }
}

作为一个测试来逐步完成:

using System.Collections.Generic;
using Xunit;

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        IEntity ientity = new TargetImpl();
        ientity.Save(new List<Job>());
    }
}

需要注意的是,上面的示例显式实现了 IEntity 接口(为简洁起见),因为此类子实现必须通过该接口显式引用。对于类似但略有不同的实现,您也可以这样做:

public class Job : IEntity
{
    public void Save<T>(List<T> entities) where T : IEntity { }
}

public class TargetImpl : IEntity
{
    public void Save<T>(List<T> entities) where T : IEntity { }
}

并且测试 impl 可以(可选)更改为:

[Fact]
public void Test1()
{
    targetImpl ientity = new TargetImpl();
    ientity.Save(new List<Job>());
}

【讨论】:

  • 欣赏 cmets 和示例。结果证明这个解决方案非常简单。我将 List 更改为 IEnumerable。我猜编译器意识到您不能通过 IEnumerable 将项目添加到列表中,因此它允许以这种方式传递列表。
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
相关资源
最近更新 更多