@Fjfgs

Объясните модификаторы доступа?

Почему создатели .NET позволяют использовать на нижних уровнях модификаторы доступа превосходящие модификатор самого этого уровня?

Пример:

internal class A
{
    public void Method()
        => Console.WriteLine("Method");
}

internal class A
{
    internal void Method()
        => Console.WriteLine("Method");
}


Оба этих кода предоставляют одни и те же возможности, не так ли?

Если да, то как лучше это написать в соответствии Code Style C#?
  • Вопрос задан
  • 251 просмотр
Решения вопроса 1
AshBlade
@AshBlade Куратор тега C#
Просто хочу быть счастливым
В спецификаци C# ECMA-334 это описывается в терминах доменов доступности - Accessibility domain.
Каждый модификатор доступа выставляет определенные ограничения на эту доступность. В результате, у тебя будут следующие "области" - A -> Method.
Главное правило - ты не можешь получить доступ к member, которые не в твоем домене.
Пример оттуда:
Example: In the following code
public class A
{
 public static int X;
 internal static int Y;
 private static int Z;
}
internal class B
{
 public static int X;
 internal static int Y;
 private static int Z;
 public class C
 {
 public static int X;
 internal static int Y;
 private static int Z;
 }
 private class D
 {
 public static int X;
 internal static int Y;
 private static int Z;
 }
}

the classes and members have the following accessibility domains:
• The accessibility domain of A and A.X is unlimited.
• The accessibility domain of A.Y, B, B.X, B.Y, B.C, B.C.X, and B.C.Y is the program text of the
containing program.
• The accessibility domain of A.Z is the program text of A.
• The accessibility domain of B.Z and B.D is the program text of B, including the program text of
B.C and B.D.
• The accessibility domain of B.C.Z is the program text of B.C.
• The accessibility domain of B.D.X and B.D.Y is the program text of B, including the program
text of B.C and B.D.
• The accessibility domain of B.D.Z is the program text of B.D. As the example illustrates, the
accessibility domain of a member is never larger than that of a containing type. For example,
even though all X members have public declared accessibility, all but A.X have accessibility
domains that are constrained by a containing type.
end example

Для твоего примера - домены доступности для этих методов одни и те же (неявно возвращается глобальный System.Void), поэтому корректная конструкция.
А вот если из публичного метода возвращать боле ограниченный тип, то будет нарушение. Т.к. возвращаешь более ограниченный из глобального.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы