Extension methods for sealed class in c#

2019-01-26 17:16发布

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 ?

3条回答
太酷不给撩
2楼-- · 2019-01-26 17:32

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.

查看更多
\"骚年 ilove
3楼-- · 2019-01-26 17:48

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-26 17:58

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.

查看更多
登录 后发表回答