什么是C#中的默认访问修饰符? [英] What are the Default Access Modifiers in C#?

查看:85
本文介绍了什么是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 {}
    }
}

的一种排序例外的是使一个属性(通常是二传),比物业本身的声明可访问更受限制的一部分:

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或
      内部声明可访问性
      默认为内部宣布
      可访问性。

  •   
  • 类成员可以有五种声明可访问性的
      和默认的是私有声明
      可访问性。 (请注意,一型
      声明为类的成员可
      有五种申报
      交通方便,而一个类型声明
      为命名空间的成员可以具有
      只有公共或内部声明
      可访问性。)

  •   
  • 结构成员可以是公共,内部或私有声明
      交通方便,默认为私有
      声明可访问性,因为结构
      是隐式密封。结构成员
      在结构中引入(即不
      通过该结构继承)不能有
      保护或受保护的内部
      声明可访问性。 (请注意,一
      键入声明为结构的成员
      可以是公共,内部或私有
      声明可访问性,而类型
      声明为命名空间中的一员
      只能有公开或内部
      声明可访问性。)

  •   
  • 接口成员隐含有公共声明可访问性。没有
      访问修饰符允许的
      接口成员声明。

  •   
  • 枚举成员隐含有公共声明可访问性。没有
      访问修饰符允许的
      枚举成员的声明。

  •   

(注意,嵌套类型会来了类成员或结构成员部分下 - 因此默认为私有可见)

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

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

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