简体   繁体   中英

Access modifiers in C#

I am teaching myself C# and I have run into a bit of an ambiguous situation.

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. So I am reading about access modifiers and according to This MSDN article the default access level is Internal. 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. 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. The C# specification states that in the absence of an access modifier on a class member it defaults to 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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