C# 中的默认访问修饰符是什么? [英] What are the default access modifiers in C#?

查看:28
本文介绍了C# 中的默认访问修饰符是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类、方法、成员、构造函数、委托和接口的默认访问修饰符是什么?

What is the default access modifier for classes, methods, members, constructors, delegates and interfaces?

推荐答案

C# 中所有内容的默认访问权限是您可以为该成员声明的最受限制的访问权限".

The default access for everything in C# is "the most restricted access you could declare for that member".

例如:

namespace MyCompany
{
    class Outer
    {
        void Foo() {}
        class Inner {}
    }
}

相当于

namespace MyCompany
{
    internal class Outer
    {
        private void Foo() {}
        private class Inner {}
    }
}

一种例外情况是使属性的一部分(通常是 setter)比声明的属性本身的可访问性更受限制:

The one sort of exception to this is making one part of a property (usually the setter) more restricted than the declared accessibility of the property itself:

public string Name
{
    get { ... }
    private set { ... } // This isn't the default, have to do it explicitly
}

<小时>

这是 C# 3.0 规范必须说的(第 3.5.1 节):


This is what the C# 3.0 specification has to say (section 3.5.1):

根据上下文成员声明发生,只有某些类型的声明可访问性是允许的.此外,当一个成员声明不包括任何访问修饰符,声明的上下文发生确定默认值声明的可访问性.

Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility.

  • 命名空间隐式具有公共声明的可访问性.没有权限命名空间上允许使用修饰符声明.
  • 在编译单元或命名空间中声明的类型可以具有 public 或内部声明的可访问性和默认为内部声明可访问性.
  • 类成员可以具有五种声明的可访问性中的任何一种并默认为私有声明可访问性.(注意一个类型声明为类的成员可以有五种声明中的任何一种可访问性,而声明的类型作为命名空间的成员可以有仅公开或内部声明可访问性.)
  • 结构成员可以声明 public、internal 或 private可访问性和默认为私有声明可访问性,因为结构是隐式密封的.结构成员在结构中引入(即,不由该结构继承)不能有受保护或受保护的内部声明的可访问性.(注意一个声明为结构成员的类型可以有公共的、内部的或私有的声明的可访问性,而类型声明为命名空间的成员只能有公共或内部声明的可访问性.)
  • 接口成员隐式具有公共声明的可访问性.不允许访问修饰符接口成员声明.
  • 枚举成员隐式具有公共声明的可访问性.不允许访问修饰符枚举成员声明.

(请注意,嵌套类型将位于类成员"或结构成员"部分下 - 因此默认为私有可见性.)

(Note that nested types would come under the "class members" or "struct members" parts - and therefore default to private visibility.)

这篇关于C# 中的默认访问修饰符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆