c# - 我可以将 C# 扩展方法的可见性限制为同一程序集中的类吗?

标签 c# .net extension-methods access-modifiers class-visibility

假设我有这些文件:

MyCode.cs

namespace MyCodeNamespace
{
  public class MyClass
  {
    //OMITTED
  }

  internal static class MyExtensions
  {
    internal static void Foo(this string str)
    {
      //OMITTED
    }
  }
}

其他代码.cs

using MyCodeNamespace;
namespace OtherCodeNamespace
{
  //OMITTED
}

这两个文件是同一个程序集的一部分。有什么方法可以使 Foo 可供 MyCode.cs 访问但不能供 OtherCode.cs 访问?我的问题类似于这个问题: C# Extension Methods only visible and accessible within one class ("private") 但它接受的答案并不是我真正想要的。我想做一个只对我正在处理的代码可见的扩展方法,根据对上述问题的回答,有人仍然可以通过添加“using”语句来访问它。有没有一种方法可以创建一个扩展方法,该方法对我的代码可见,在其他任何地方,甚至对同一程序集中的另一个类都不可见?

我问是因为调用扩展方法的语法很方便,对我正在做的事情很有用(否则我只是创建一个私有(private)方法),但我不想让其他人看到它并且从他们的代码中使用它,以防它没有按照他们假设的那样做。多亏了 Visual Studio 的智能感知,我的扩展方法目前显示在可用方法列表中(以及添加它们所在的命名空间的选项)。

最佳答案

.NET 平台中没有命名空间限制访问修饰符这样的东西。 From the docs

public : Access is not restricted.
protected : Access is limited to the containing class or types derived from the containing class.
Internal : Access is limited to the current assembly.
protected internal: Access is limited to the current assembly or types derived from the containing class.
private : Access is limited to the containing type.

这就是您需要处理的全部内容。所以答案是

关于c# - 我可以将 C# 扩展方法的可见性限制为同一程序集中的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28117698/

相关文章:

c# - 重新实例化线程

c# - 为什么不能直接调用扩展方法?

c# - 单个泛型的 Comparable 和 Nullable 约束

c# - 为类型 T 编写扩展方法;如何为 T 的字段添加类型约束?

c# - DbContext 没有编译?

.net - 是否有一个很好的 .Net CSS 聚合器可以组合样式表并缩小它们?

c# - 画一个矩形

c# - 如何在UWP中的类库项目中使用Resources.resw?

c# - Newtonsoft JSON - 动态对象

c# - 等待 "Unable to cast COM object"异常