What does the “private” modifier do?

2020-04-01 08:42发布

Considering "private" is the default access modifier for class Members, why is the keyword even needed?

13条回答
女痞
2楼-- · 2020-04-01 09:02

As pointed out by Jon Skeet in his book C# In Depth, there is one place in C# where the private keyword is required to achieve an effect.

If my memory serves correctly, the private keyword is the only way to create a privately scoped property getter or setter, when its opposite has greater than private accessibility. Example:

public bool CanAccessTheMissileCodes
{
    get { return canAccessTheMissileCodes; }
    private set { canAccessTheMissileCodes = value; }
}

The private keyword is required to achieve this, because an additional property accessability modifier can only narrow the scope, not widen it. (Otherwise, one might have been able to create a private (by default) property and then add a public modifier.)

查看更多
Juvenile、少年°
3楼-- · 2020-04-01 09:03

Some coding styles recommend that you put all the "public" items first, followed by the "private" items. Without a "private" keyword, you couldn't do it that way around.

Update: I didn't notice the "c#" tag on this so my answer applies more to C++ than to C#.

查看更多
闹够了就滚
4楼-- · 2020-04-01 09:05

Using private explicitly signals your intention and leaves clues for others who will support your code ;)

查看更多
甜甜的少女心
5楼-- · 2020-04-01 09:06

It's for you (and future maintainers), not the compiler.

查看更多
我想做一个坏孩纸
6楼-- · 2020-04-01 09:08

I usually leave private out but I find it useful for lining up code:

private   int    x;
public    string y;
protected float  z;

VS:

int x;

public    string y;
protected float  z;
查看更多
ゆ 、 Hurt°
7楼-- · 2020-04-01 09:14

For completenes. And some people actually prefer to be explicit in their code about the access modifiers on their methods.

查看更多
登录 后发表回答