在我们的一个项目中,有很多代码看起来像这样:

internal static class Extensions
{
    public static string AddFoo(this string s)
    {
        if (s == null)
        {
            return "Foo";
        }

        return $({s}Foo);
    }
}

除了“以后更容易将类型公开”之外,还有其他明确的原因吗?

我怀疑它只在非常奇怪的边缘情况下(在Silverlight反射)或根本不重要。


当前回答

如果类是内部的,那么从可访问性的角度来看,将方法标记为内部的还是公共的并不重要。但是,如果类是公共的,那么使用您将使用的类型仍然是好的。

虽然有些人说,这使得从内部到公开的过渡更加容易。它也作为方法描述的一部分。内部方法通常被认为是不安全的,不受约束的访问,而公共方法被认为是(大多数)自由游戏。

通过像在公共类中那样使用内部类或公共类,可以确保您传达了预期的访问风格,同时也简化了将来使类成为公共类所需的工作。

其他回答

出于与在任何其他类中使用公共方法相同的原因——因此它们对包含类型外部是公共的。

类型的访问修饰符与其成员的访问修饰符完全没有关系。这两个决定是完全独立的。

仅仅因为类型和成员的修饰符的某些组合产生了看似相同的结果(或者其他人称之为“有效”)并不意味着它们在语义上是相同的。

实体的本地访问修饰符(在代码中声明)和它的全局有效访问级别(通过包含链评估)也是完全不同的东西。一间上了锁的大楼里的开放式办公室仍然是开放的,即使你不能从街上真正进入它。

不要考虑最终结果。首先,想想你在当地需要什么。

公众的公众:经典的情况。 Public的Internal:类型是Public,但是你想在程序集中获得一些半合法的访问权限来做一些古怪的事情。 内部的公共:你隐藏了整个类型,但在程序集中它有一个经典的公共表面 内部的内部:我想不出任何现实世界的例子。也许很快就会成为公众的内部信息?

内部的公众vs内部的内部是一个虚假的困境。这两个词的意思完全不同,应该在各自的情况下使用,不能重叠。

I often mark my methods in internal classes public instead of internal as a) it doesn't really matter and b) I use internal to indicate that the method is internal on purpose (there is some reason why I don't want to expose this method in a public class. Therefore, if I have an internal method I really have to understand the reason why it's internal before changing it to public whereas if I am dealing with a public method in an internal class I really have to think about why the class is internal as opposed to why each method is internal.

There does be a difference. In our project we have made a lot of classes internal, but we do unit test in another assembly and in our assembly info we used InternalsVisibleTo to allow the UnitTest assembly to call the internal classes. I've noticed if internal class has an internal constructor we are not able to create instance using Activator.CreateInstance in the unit test assembly for some reason. But if we change the constructor to public but class is still internal, it works fine. But I guess this is a very rare case (Like Eric said in the original post: Reflection).

它是一样的,public方法将被标记为内部的,因为它在内部类中,但它有一个优点(正如你所说),如果你想将类标记为公共的,你必须修改更少的代码。

我怀疑“以后公开类型会更容易吗?”

作用域规则意味着该方法只能作为内部方法可见——因此将方法标记为公共方法还是内部方法并不重要。

我想到的一种可能是,类是公共的,后来改为内部的,开发人员没有费心去更改所有的方法可访问性修饰符。