Extension methods for sealed class in c#

2019-01-26 17:34发布

问题:

I have this sealed class,

public sealed class A
{
    public string AName {get;set;}
}

and someone can write an extension method for it like this:

public static class Extensions
{
   public static void ExtensionMethodForA (this A a)
   {
      Console.WriteLine("A's Extension method!");
   }
}

The question is, how do you prevent that ?

回答1:

You don't. You can't. And you shouldn't want to.

Instance methods are always preferred to extension methods, so it should not present a conflict. Other than that, they are mere syntax / convenience. Stop trying to make life inconvenient for callers.



回答2:

You might be confused by the term "extension method". It is not a method in the class or even a derived class; It is an operation on a type. It has no access to the private, protected or internal members of the class hierarchy and therefore the class is still sealed.

So, you can't and don't need to.



回答3:

There would be no point. Any user could still create a static class which implemented a method which used your class type.

They would just leave out the 'this' out of the declaration, and callers would have to explicitly pass the object, rather than using the simpler . syntax. The end result would be identical.

Extension methods are just a nicer way of expressing what I've just described, which will always be possible anyway.