C#中密封类的扩展方法 [英] Extension methods for sealed class in c#

查看:231
本文介绍了C#中密封类的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个sealed课,

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.

这篇关于C#中密封类的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆