gpt4 book ai didi

c# - 通用 T GetByID(K ID_)

转载 作者:太空狗 更新时间:2023-10-30 00:45:56 24 4
gpt4 key购买 nike

我正在尝试使用 Entity Framework 实现通用存储库。

我的存储库定义为:

    public class GenericRepository<T> : IRepository<T> where T : class

我想添加一个通用的 GetByID,其中传入的 ID 类型也是通用的。我真的不希望我的业务逻辑告诉我类型是例如....

    _repository.GetByID<int>(123);

我想隐藏 tyoe 定义,但不知道在哪里或如何做。

Stackoverflow 上的大多数帖子似乎只是将其 ID 作为整数。我不希望这样,因为您的标识符并不总是整数!

关于这个问题有什么想法吗?

最佳答案

这是我做的

interface IRepository<TEntity, TKey> {
TEntity GetById(TKey id);
}

然后我继承这个接口(interface)

class Person {
int ID;
}
interface IPersonRepository : IRepository<Person, int> { ... }

这使得它对 DI/IoC 和单元测试也非常友好。

关于c# - 通用 T GetByID<K>(K ID_),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479728/

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