What is the meaning of the planned “private protec

2019-01-10 02:32发布

问题:

As part of the Roslyn documentation on GitHub, there's a page called Language feature implementation status, with planned language features for C# and VB.

One feature I couldn't wrap my head around was private protected access modifier:

private protected string GetId() { … } 

There is also a page of C# Language Design Notes, which explains many new features, but not this one.

Eric Lippert said in a comment:

Your error is in thinking of the modifiers as increasing restrictions. The modifiers in fact always decrease restrictions. Remember, things are "private" by default; only by adding modifiers do you make them less restricted.

What is the meaning of private protected? When might I use it?

回答1:

According to "Professional C# 2008" by De Bill Evjen and Jay Glynn, page 1699:

private protected - "only derived types within the current assembly"

C++/CLI has a similar feature - Define and Consume Classes and Structs (C++/CLI) > Member visibility:

private protected -or- protected private - Member is protected inside the assembly but private outside the assembly.



回答2:

Here are all access modifiers in Venn diagrams, from more limiting to more promiscuous:

private:

private protected: - added in C# 7.2

internal:

protected:

protected internal:

public:



回答3:

This is just to provide a graph (made with http://ashitani.jp/gv/) of the different accessibility levels (images do not fit in comments).

Each arrow means "is more restrictive than".

The CLR names are Private, FamilyANDAssembly, Assembly, Family, FamilyORAssembly, Public.


Much later edit: It turned out this nice new access level (with a really poor name) was not eventually included in C# 6.0. It is supported only from C# 7.2 (and I see you updated your question "tags").



回答4:

It's just a guess, but from a name you could possibly guess it's a more restricted version of protected, (or more relaxed version of private if you wish). And only reasonable variant of it is restricting protected behaviour to assembly.

Possible usage: then you want to have protected for internal implementation, but not for external uses (and you don't want sealing the class).

P.S. It always existed in CLR, but not in C#. It's a combination of protected and internal, quote:

CLR also supports “Family and assembly” access type. This means that the method is accessible from within the declaring type, nested and derived types but only if they’re declared in the same assembly. Well, apparently C# team didn’t think of this as a very useful feature so it’s not supported in this language.



回答5:

"May be" only visible to subclasses that are in same assembly. This makes it a little restricted than protected.



回答6:

See the spec for the "private protected" feature:

The intuitive meaning of private protected is “accessible within this assembly by types derived from the containing class”.