简体   繁体   English

C#中的访问修饰符

[英]Access modifiers in C#

I am teaching myself C# and I have run into a bit of an ambiguous situation. 我正在教自己C#,我遇到了一些模棱两可的情况。

What I'm trying to do is create a container class for some data, fairly straight forward but I am trying to respect encapsulation and have the data accessible via setters and getters only. 我正在尝试做的是为一些数据创建一个容器类,相当直接,但我试图尊重封装,并且只能通过setter和getter访问数据。 So I am reading about access modifiers and according to This MSDN article the default access level is Internal. 所以我正在阅读有关访问修饰符的内容,根据此MSDN文章 ,默认访问级别为内部。 I am from Java-land so I am not familiar with internal, however from the resources on that page, it looks like Internal is more permissive than I want to be. 我来自Java-land所以我不熟悉内部,但是从该页面上的资源来看,内部看起来比我想要的更宽松。 So I want to set things as private. 所以我想把东西设为私人。

My confusion arises from the code example here . 我的困惑来自这里的代码示例。 it looks like if I do 看起来如果我这样做

class whatever {
    private int thing;
    string ambiguous; 
}

the ambiguous variable will be private, not internal. 模棱两可的变量将是私有的,而不是内部的。

Does it actually work like that? 它真的像那样工作吗? Or is the second example mis-written? 或者第二个例子写错了?

The field ambiguous is not ambiguous at all. 该领域ambiguous并不含糊。 The C# specification states that in the absence of an access modifier on a class member it defaults to private . C#规范声明,如果类成员没有访问修饰符,则默认为private

The default access level on top-level types is internal. 顶级类型的默认访问级别是内部的。

class Foo {
    int bar;
    class Nested {
        int baz;
    }
}

is equivalent to 相当于

internal class Foo {
    private int bar;
    private class Nested {
        private int baz;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM