嵌套 types/type 成员的可访问性传播

accessibility propagation of nested types/type members

根据我的理解,如果我们在 T1 中有一些类型 T1 和嵌套类型 T2(或成员 M2),[= 的可访问性14=] (M2) 是 T1T2.

的可访问性中的最小值

我所说的最低限度是指通过在以下架构中搜索两个可访问性级别并选择较低的可访问性级别获得的可访问性:

public
|
protected internal
|            |
internal     protected
       |     |
 (protected AND internal)*
             |
             private

(* 这不能通过访问修饰符直接定义。它只允许从程序集中定义的继承类型进行访问。)

示例:

internal class T1
// internal
{
    public int i;
    // internal

    protected class T2
    // protected and internal
    {
        public int j;
        // protected and internal
    }
}

对吗?如果不是,这条规则有哪些例外情况?

我问是因为在 Wouter de Kort 的 "Programming in C#: Exam Ref 70-483" 书中写道:

Something to keep in mind is that the access modifier of the enclosing type is always taken into account. For example, a public method inside an internal class has an accessibility of internal. There are exceptions to this (for example, when an internal class implements a public interface or when a class overrides a public virtual member of a base class), so you need to keep track of those things when determining the accessibility of a type you need.

但是没有进一步解释那是什么意思,我也不明白。

  1. 如果内部 class 实现了 public 接口,则此 class 只能在程序集内使用。那么实现的接口方法如何比内部更易访问呢?跟静态方法有关系吗?

  2. 如果 child class 覆盖基 class 的 public 方法,则 child 只能在其规定的水平。那么,如果 child 不是,重写的方法如何更容易访问呢?跟静态方法有关系吗?

how can the implemented interface methods be more accessible than internal?

设置如下:嵌套的私有 class 实现了 public 接口。

public interface IVisible {
    void CallMe();
}

public class Outer {
    private class Hidden : IVisible {
        public void CallMe() {
            Console.WriteLine("I'm hidden!");
        }
    }
    public static IVisible GetObject() {
        return new Hidden();
    }
}

此 class 的用户通过将其转换为 public 接口 IVisible 获得对 HiddenCallMe() 方法的访问权:

IVisible obj = Outer.GetObject();
obj.CallMe(); // prints "I'm hidden!"

how can the overridden method be more accessible if the child is not?

相同的设置适用:您创建一个可访问的方法,该方法 returns 不可访问类型 (Hidden) 的实例作为其 public 基础 class 的对象或它的 public 接口(即假设 IVisible 是一个 class,而不是接口)。

本质上,public 接口(例如 IVisible)提供了一个 "window" 到非 public 实现(例如 Hidden)。这是一种非常强大的技术,用于控制对您希望公开的行为的访问。