作者:闻雪儿1116_414 | 来源:互联网 | 2023-08-27 19:47
Ihavejuststartedtolookat.NET3.5sopleaseforgivemeifthistypeofquestionhavebeenaske
I have just started to look at .NET 3.5 so please forgive me if this type of question have been asked before. I am struggling with a decent usage for extension methods, in that I have just downloaded suteki shop an MVC ecommerce offering. In this project there is a pretty standard Repository pattern that extends IRepository.
我刚刚开始研究.NET 3.5,如果之前已经提出这类问题,请原谅我。我正在努力使用扩展方法,因为我刚刚下载了suteki商店的MVC电子商务产品。在这个项目中,有一个非常标准的Repository模式,它扩展了IRepository。
In order to extend the basic functionality exposed by this interface, extention methods are used i.e.:
为了扩展该接口所暴露的基本功能,使用了扩展方法,即:
public static class CategoryRepositoryExtensions
{
public static Category GetRootCategory(this IRepository categoryRepository)
{
return categoryRepository.GetById(1);
}
}
Now this is all well and good, but Interfaces, as far as I am concerned act as contracts to the objects that implement them.
现在这一切都很好,但就我而言,Interfaces充当了实现它们的对象的契约。
The fact that the repository has been interfaced out suggests an attempt at a data layer agnostic approach. That said, if I were to create my own data layer I would be confused as to what extension methods I would have to create to ensure I have fulfilled the contractual requirement I have to the classes that implement my repository classes.
存储库已经接口的事实表明尝试采用数据层不可知的方法。也就是说,如果我要创建自己的数据层,我会对我必须创建的扩展方法感到困惑,以确保我已经完成了对实现我的存储库类的类的合同要求。
It seems that the older way of creating an IRepository and then extending that allows a much better visibility of what is required e.g.
似乎创建IRepository然后扩展的旧方法允许更好地查看所需的内容,例如,
ICategoryRepoitory : IRepository
{
Category GetRootCategory();
}
So I guess my question is does this use of Extention methods seem wrong to anyone else? If not, why? Should I not be moaning about this?
所以我想我的问题是,对于其他人来说,使用Extention方法似乎是错误的吗?如果没有,为什么?我不应该抱怨这个吗?
EDIT:
The above example does seem to be a good example of why extention methods can be very helpful.
上面的例子似乎是一个很好的例子,说明为什么扩展方法可以非常有用。
I suppose my issue is if data access specific implementations were stuck in the extention method in the data access mechanisms assembly.
我想我的问题是,如果数据访问特定的实现被卡在数据访问机制程序集中的扩展方法中。
That way if I were to swap it out for another mechanism I would have to create a similar extention method in that assembly.
这样,如果我将其换成另一种机制,我将不得不在该程序集中创建一个类似的扩展方法。
4 个解决方案