可以将扩展方法应用于接口吗? (C#问题)
这是为了实现以下目的:
创建一个ITopology界面
为此接口创建一个扩展方法(例如public static int CountNodes(此ITopology拓扑结构))
那么当创建实现ITopology的类(例如MyGraph)时,它将自动地具有Count Nodes扩展。
这样,实现接口的类将不一定要有一个set类名称来与扩展方法中定义的类对齐。
Is it possible to apply an extension method to an interface? (C# question)
That is for example to achieve the following:
create an ITopology interface
create an extension method for this interface (e.g. public static int CountNodes(this ITopology topologyIf) )
then when creating a class (e.g. MyGraph) which implements ITopology, then it would automatically have the Count Nodes extension.
This way the classes implementing the interface would not have to have a set class name to align with what was defined in the extension method.
最满意答案
当然可以 大多数Linq是围绕接口扩展方法构建的。
接口实际上是扩展方法发展的推动力之一; 由于它们不能实现任何自己的功能,扩展方法是将实际代码与接口定义相关联的最简单方法。
有关IEnumerable<T>的扩展方法的整个集合,请参阅Enumerable类。 要实现一个,它与实现一个类相同:
public static class TopologyExtensions { public static void CountNodes(this ITopology topology) { // ... } }就接口而言,扩展方法没有什么特别的区别; 扩展方法只是一种静态方法,编译器应用一些句法糖,使其看起来像方法是目标类型的一部分。
Of course they can; most of Linq is built around interface extension methods.
Interfaces were actually one of the driving forces for the development of extension methods; since they can't implement any of their own functionality, extension methods are the easiest way of associating actual code with interface definitions.
See the Enumerable class for a whole collection of extension methods built around IEnumerable<T>. To implement one, it's the same as implementing one for a class:
public static class TopologyExtensions { public static void CountNodes(this ITopology topology) { // ... } }There's nothing particularly different about extension methods as far as interfaces are concerned; an extension method is just a static method that the compiler applies some syntactic sugar to to make it look like the method is part of the target type.
更多推荐
发布评论