假设我有这些文件:
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/