ChatGPT解决这个技术问题 Extra ChatGPT

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 (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.


A
Aaronaught

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.


Re: "Of course" - I think the question reveals the architecture smell you implicitly mention. If you can have extensions on interfaces, why can't interfaces contain implemented methods? It's understandable to think either interfaces should be able to have concrete methods, or, once you know they can't, think that extension methods shouldn't be allowed as a viable kludge. (But they are. Not arguing your excellent answer, just the "of course" and the link to IEnum, not LINQ. ;^D) Something's smelly there!
Would like to add news to @ruffin comment that now you can add default implementations to C# interface methods. Source: devblogs.microsoft.com/dotnet/…
@ruffin I found this the most confusing architectural decision in C#. Sometimes it ends up half-class half-interface structure messing all around. Still, I believe it can be useful when approached from functional programming point of view, and used for introducing utilities to interfaces rather than implementing functionality.
@ruffin There is this other edge. If you are working with libraries (by principle, when working with libraries you should work with interfaces), the extension gives you the opportunity to override it, right? And interfaces can't have a 'virtual' method (well, with C# 8 where you can declare a body, they can). So, this is a powerfull option. Again, this is an option, it's just a weapon in the arsenal. In that prespective, it's an incredible thing, isn't it?