Can extension methods be applied to interfaces?

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 (eg public static int CountNodes(this ITopology topologyIf) )

  • then when creating a class (eg 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.


    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.

    链接地址: http://www.djcxy.com/p/17448.html

    上一篇: jQuery new Object .bind

    下一篇: 扩展方法可以应用于接口吗?