gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:08:20 27 4
gpt4 key购买 nike

我有一个静态类 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com