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

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

        return $({s}Foo);
    }
}

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

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


当前回答

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 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.

我今天真的很纠结这个问题。到目前为止,如果类是内部的,我会说方法都应该被标记为内部的,并且会认为其他任何东西都只是糟糕的编码或懒惰,特别是在企业开发中;然而,我必须子类化一个公共类并重写它的一个方法:

internal class SslStreamEx : System.Net.Security.SslStream
{
    public override void Close()
    {
        try
        {
            // Send close_notify manually
        }
        finally
        {
            base.Close();
        }
    }
}

方法必须是公共的,这让我想到,将方法设置为内部没有逻辑意义,除非它们真的必须是,就像Eric Lippert说的那样。

直到现在,我从来没有真正停下来思考过这个问题,我只是接受了它,但在阅读了Eric的帖子后,它真的让我思考,经过很多深思熟虑后,它有很多意义。

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

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

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

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).