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

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

        return $({s}Foo);
    }
}

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

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


当前回答

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

其他回答

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方法将被标记为内部的,因为它在内部类中,但它有一个优点(正如你所说),如果你想将类标记为公共的,你必须修改更少的代码。

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

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

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

在某些情况下,也可能是内部类型实现了一个公共接口,这意味着在该接口上定义的任何方法仍然需要声明为公共。

I think I have an additional opinion on this. At first, I was wondering about how it makes sense to declare something to public in an internal class. Then I have ended up here, reading that it could be good if you later decide to change the class to public. True. So, a pattern formed in my mind: If it does not change the current behavior, then be permissive, and allow things that does not makes sense (and does not hurt) in the current state of code, but later it would, if you change the declaration of the class.

是这样的:

public sealed class MyCurrentlySealedClass
{
    protected void MyCurretlyPrivateMethod()
    {
    }
}

According to the "pattern" I have mentioned above, this should be perfectly fine. It follows the same idea. It behaves as a private method, since you can not inherit the class. But if you delete the sealed constraint, it is still valid: the inherited classes can see this method, which is absolutely what I wanted to achieve. But you get a warning: CS0628, or CA1047. Both of them is about do not declare protected members in a sealed class. Moreover, I have found full agreement, about that it is senseless: 'Protected member in sealed class' warning (a singleton class)

因此,在这个警告和相关的讨论之后,我决定在一个内部类中使所有内容都变得内部或更少,因为它更符合那种思维方式,而且我们不会混合不同的“模式”。