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

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

        return $({s}Foo);
    }
}

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

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


当前回答

Internal表示只能从同一程序集中访问成员。该程序集中的其他类可以访问内部公共成员,但不能访问私有成员或受保护成员(无论是否是内部成员)。

其他回答

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)

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

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

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

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

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

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

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

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

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

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.