简体   繁体   English

是否使用扩展方法将实现添加到接口Anti-OOP?

[英]Is using Extension methods to add implementation to an interface Anti-OOP?

I have an Interface. 我有一个界面。 Due to a new requirement, the interface now has a single method that could be implemented. 由于新的要求,该接口现在具有可以实施的单个方法。

public static string ToEntityConnectionString(this IEnvironmentProvider provider)
//Converts a standard connection string to EntityFramework compatible string

I could convert the interface to an Abstract class, albeit I'm now restricting myself to this class as the inheriting class. 我可以将接口转换为Abstract类,尽管现在我将自己限制为继承类。 Although, this interface is currently used for Dependency Injection alone. 虽然,此接口当前仅用于依赖关系注入。

After some thought, I realized I could append the functionality to the interface via an Extension method. 经过一番思考,我意识到我可以通过扩展方法将功能附加到接口上。 It seems to good to be true. 看起来不错,这是真的。 Adding implementation to an interface? 将实现添加到接口? Is it considered a bad practice to do such a thing? 做这样的事情被认为是不好的做法吗? If so, why? 如果是这样,为什么? Considering the circumstances, what should be used instead? 考虑到情况,应该使用什么代替呢?

When you have an extension method on an interface you shouldn't think of it as adding an implementation to that interface. 当接口上具有扩展方法时,不应将其视为向该接口添加实现。 It is just a static helper method that takes an interface, and does all of it's work based on the Interface's exposed members. 它只是一个采用接口的静态帮助器方法,并根据接口的公开成员来完成所有工作。 This is something you see quite a lot of in OO design; 在OO设计中,您会看到很多。 it's not contrary to OO principles. 这不违反面向对象原则。 The 'extension' part just makes it look prettier and makes it easier to find/type out. “扩展”部分使其看起来更漂亮,并且更易于查找/键入。 If you start to actually think of the extension method as a part of the interface you'll have bigger problems, because it really isn't. 如果您开始真正将扩展方法视为接口的一部分,则会遇到更大的问题,因为实际上并非如此。

I see extension methods as simply helper methods who could just as easily be done with copy paste code by the users of the class. 我将扩展方法视为简单的辅助方法,该类用户可以轻松地使用复制粘贴代码来完成。 If the functionality can be performed WITHOUT accessing non-public attributes, then is there really anything new being provided that would justify adding it to the interface, then no. 如果可以在不访问非公共属性的情况下执行该功能,那么确实提供了任何新的方法来证明将其添加到接口是合理的,然后否。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM