将List <iinfrastructureentity>转换为List <tentity>,其中泛型类型TEntity必须实现该接口

时间:2017-10-07 05:08:13

标签: c# asp.net generics interface

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

无法隐式转换类型&#39; System.Collections.Generic.List<IInfrastructureEntity>&#39;到&#39; System.Collections.Generic.List<TEntity>&#39;

如何明确进行转换?

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);
    }

}

1 个答案:

答案 0 :(得分:2)

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

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

问题是DataSource.Members的类型是List<IInfrastructureEntity>,而预期返回的类型是List<TEntity>。实际上,每个Entity都应该实现IInfrastructureEntity,因为您已将其声明为where TEntity : IInfrastructureEntity。但是,即使类型实现此接口,也不意味着此类型可以隐式转换为TEntity对象。这就是你需要显式演员的原因。

相关问题