gpt4 book ai didi

c# - 特定通用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 14:04:16 24 4
gpt4 key购买 nike

我正在重构各种类型的所有存储库接口(interface)。它们中的大多数包含非常相似的方法,如 Add、Update,但有些方法只对特定类型有意义。这是一个最佳实践问题。

我想过使用泛型来理顺事情。

 public interface IRepository<T>
{
T Get(int id);
void Add(T x);
}

但现在说具体的方法。我当然可以将接口(interface)“子类化”,但我的情况并没有比以前好。我会有这样的代码:

 IUserRepository<User> users;

一个巧妙的方法是,如果我可以有多个约束,例如:

 public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);
}

public partial interface IRepository<T> where T: User
{
T Get(Guid id);
}

public partial interface IRepository<T> where T: Order
{
T Get(string hash);
}

但是编译器提示继承冲突。另一种方法是对方法进行约束:

 public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);

T Get(Guid id) where T: User;
T Get(string hash) where T: Order;
}

但这并不完全是这些工作的方式。编译器理解不了我的意图,当然想要方法的类型定义。

现在我只有抛出 NotImplemented 的方法。丑。

我正在寻找一个能让我踢自己的解决方案。

最佳答案

public interface IRepository<TEntity, TId>
{
TEntity Get(TId id);
void Add(T x);
}

public class UserRepository : IRepository<User, Guid>
{
public User Get( Guid id )
{
// ...
}

public void Add( User entity)
{
// ...
}
}

public class OrderRepository : IRepository<Order, string>
{
//...
}

关于c# - 特定通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2365068/

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