c# - 将 List<IInfrastructureEntity> 转换为 List<TEntity>,其中泛型类型 TEntity 必须实现该接口(interface)

标签 c# asp.net generics interface

我有一个静态类DataSource从文件中提取请求的数据并将其作为 List<IInfrastructureEntity>. 返回在 TestRepository (如下),我使用通用 TEntity ,确定其类类型并从 DataSource 中提取相应的数据或者,至少尝试这样做。相反,我在每个 return 语句上收到以下编译时错误。即使任何 TEntity必须实现IInfrastructureEntity .

无法隐式转换类型“System.Collections.Generic.List<IInfrastructureEntity>” '到'System.Collections.Generic.List<TEntity> '

如何明确进行该转换?

public class TestRepository<TEntity> : IRepository<TEntity> where TEntity : IInfrastructureEntity
{
    public List<TEntity> GetData()
    {
        TEntity checkType = default(TEntity);
        if (checkType is Member) return DataSource.Members;
        if (checkType is MenuItem) return DataSource.MenuItems;
        if (checkType is CRAWApplication) return DataSource.CRAWApplications;
        if (checkType is CRAWEntitlement) return DataSource.CRAWEntitlements;
        if (checkType is FOXGroup) return DataSource.FOXGroups;

        throw new NotSupportedException( checkType.ToString() + " is not yet supported");
    }

    public List<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
    {
        return GetData().AsQueryable().Where(predicate);
    }

}

最佳答案

您可以通过在返回的每个列表中强制执行显式转换来解决此问题:

if (checkType is Member) return DataSource.Members.Cast<TEntity>().ToList();

问题在于 DataSource.Members 的类型是 List<IInfrastructureEntity> ,而预期返回的类型是 List<TEntity> 。确实每个Entity应该实现IInfrastructureEntity正如您所说的 where TEntity : IInfrastructureEntity 。然而,即使一个类型实现了这个接口(interface),也不意味着这个类型可以隐式转换为TEntity。目的。这就是为什么您需要显式强制转换。

关于c# - 将 List<IInfrastructureEntity> 转换为 List<TEntity>,其中泛型类型 TEntity 必须实现该接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616867/

相关文章:

c# - 将文件添加到 Flurl 多部分 POST 请求时 IFormFileCollection 为空

c# - 如何使用 C# 获取 XML 根节点?

c# - 按可以为 null 的父对象对 IList<Person> 进行排序

c# - 带有泛型的类型化类

java - Spring中如何使用泛型?

c# - 最小起订量特定列表项的检索

c# - 当没有要求和的内容时,Linq .Sum() 函数失败

c# - 如果 web.config 中的连接字符串已加密,外部用户是否可以访问该站点?

ASP.NET Web 应用程序 (MVC) 部署自动化和 Subversion

java - ? Java super 字符串下界