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