具有继承类的 IRepository

发布于 2024-10-10 13:37:49 字数 432 浏览 3 评论 0原文

为了与数据输入的存储库模式保持一致,我有一个关于使用继承类的问题。例如,假设我要上课...

class Employee

IEmployeeRepository
{
 Add(Employee employee);
}

这工作正常,到目前为止没有任何问题...但现在让我们说我继续...

class Manager : Employee

好吧,现在让我们假设我永远不需要输入与经理不同的经理员工?这里最好的方法是什么?诸如 .. 之类的场景

IEmployeeRepository
{
 Add<T>(T employee) where T : Employee
}

是否是最好的方法,或者我是否需要为每种类型抽象一个不同的存储库?

In keeping with the Repository pattern of data input, I've a question in regards to using inherited classes. For instance, suppose I would have the class...

class Employee

IEmployeeRepository
{
 Add(Employee employee);
}

This works fine, nothing wrong with it so far... but now let's say I continue on..

class Manager : Employee

Okay, now let's assume that I never need to enter a manager different than an Employee? What's the best approach here? Would a scenario such as ..

IEmployeeRepository
{
 Add<T>(T employee) where T : Employee
}

Be the best approach, or do I need to abstract a different repository for each type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅听莫相离 2024-10-17 13:37:49

如果他们都是员工,我可能会创建一个界面并将其限制于此。例如:

IEmployeeRepository
{
 Add<T>(T employee) where T : IEmployee
}

If they are all employees, I would probably create an interface and constrain it to that. For example:

IEmployeeRepository
{
 Add<T>(T employee) where T : IEmployee
}
止于盛夏 2024-10-17 13:37:49

如果事情的处理方式不同,那么您应该为新类型创建另一个存储库。

如果两者从来没有不同的逻辑(并且他们确实不应该考虑经理在您的情况下仍然是员工),那么您可以重新使用您已有的内容。您甚至不需要更改代码(只要 Manager 继承自 Employee 类):

public interface IEmployeeRepository
{
    Add(Employee employee);
}

应该可以正常工作。

If things are being handled differently, then you should create another Repository for the new type.

If the two never have different logic (and they really shouldn't considering a Manager is still an Employee in your case), then you can re-use what you already have. You shouldn't even need to change the code (as long as Manager inherits from the Employee class):

public interface IEmployeeRepository
{
    Add(Employee employee);
}

Should work just fine.

寂寞清仓 2024-10-17 13:37:49

假设我永远不需要
输入一个不同于
员工

所以你没有抽象。您只有一个Employee,并且您需要一个存储库。

我需要抽象一个不同的
每种类型的存储库?

是的,如果您有几个子类的抽象。要点是通常不需要仅用于子类的抽象类的存储库。

let's assume that I never need to
enter a manager different than an
Employee

So you do not have an abstraction. You only have an Employee and you need a repository for that.

do I need to abstract a different
repository for each type?

Yes if you have an abstraction of a few subclasses. The point is you normally do not need a repository for abstract classes only for subclasses.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文