简体   繁体   中英

Extension methods for sealed class in c#

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 ?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM