gpt4 book ai didi

c#如何处理这个泛型约束?

转载 作者:行者123 更新时间:2023-12-02 05:21:16 24 4
gpt4 key购买 nike

我有三个处理三个基类的通用存储库:

public class Entity
{
public int Id { get; set; }
}

public class Repository
{
public TEntity[] GetAll<TEntity>() where TEntity : Entity
{
return _context.Set<TEntity>.ToArray();
}
}

public class ArchiveEntity : Entity
{
public bool Deleted { get; set; }
}

public class ArchiveRepository
{
public TEntity[] GetAll<TEntity>() where TEntity : ArchiveEntity
{
return _context.Set<TEntity>.Where(x => x.Deleted == false).ToArray();
}
}

public class LogicalStorageEntity : ArchiveEntity
{
public int StorageId { get; set; }
}

public class LogicalStorageRepository
{
public int CurrentStorageId { get; set; }

public TEntity[] GetAll<TEntity>() where TEntity : LogicalStorageEntity
{
return _context.Set<TEntity>
.Where(x => x.Deleted == false)
.Where(x => x.StorageId = CurrentStorageId)
.ToArray();
}
}

有没有办法让一个存储库根据基类以不同方式过滤实体?看起来像的东西:

public class Entity
{
public int Id { get; set; }
}

public class ArchiveEntity : Entity
{
public bool Deleted { get; set; }
}

public class LogicalStorageEntity : ArchiveEntity
{
public int StorageId { get; set; }
}

public class UniversalRepository
{
public TEntity[] GetAll<TEntity>() where TEntity : Entity
{
if (typeof(TEntity) is LogicalStorageEntity)
{
return _context.Set<TEntity>
.Where(x => /* how to filter by x.Deleted */)
.Where(x => /* how to filter by x.StorageId */)
.ToArray();
}

if (typeof(TEntity) is ArchiveEntity)
{
return _context.Set<TEntity>
.Where(x => /* how to filter by x.Deleted */)
.ToArray();
}

return _context.Set<TEntity>.ToArray();
}
}

编辑。问题不在于如何检查实体是否属于特定类型。真正困难的部分是当您知道可以通过 Deleted 或其他一些属性过滤实体时应用过滤器。由于存在限制 TEntity : Entity ,您无法访问 Deleted 属性。

最佳答案

您可以通过转换来实现,但我会质疑仅执行非泛型功能的泛型方法的用处。

我的意思是,如果没有为不止一种类型执行的通用代码,那么在我看来,您实际上也可以在特定于类的派生中实现它。

关于c#如何处理这个泛型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13801957/

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