扩展方法可以应用于接口吗?(Can extension methods be applied to interfaces?)

编程入门 行业动态 更新时间:2024-10-23 01:52:26
扩展方法可以应用于接口吗?(Can extension methods be applied to interfaces?)

可以将扩展方法应用于接口吗? (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.

更多推荐

本文发布于:2023-08-07 20:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   接口   方法   extension   applied

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!