アクセス修飾子の確認
サンプル
プロジェクトを2つ用意して,アクセス権を確認した。
ClassLibrary1
namespace AccessApp { public class Server { public void PublicMethod() { } // どこからでもアクセスできる internal void InternalMethod() { } // アセンブリ外からはアクセスできない private void PrivateMethod() { } // そのコンテナ内からしかアクセスできない protected void ProtectedMethod() { } // privateに加えて、継承したクラスからもアクセスできる protected internal void ProtectedInternalMethod() { } // protectedに加えて,同じアセンブリからもアクセスできる(Protected or Internal) protected private void ProtectedPrivateMethod() { } // memo: C#7.2以降 // protectedと同様だが,継承したクラスであっても別のアセンブリからはアクセスできない(Protected and Internal) } public class ExServer : Server { public void TestAccess() { this.PublicMethod(); this.InternalMethod(); //this.PrivateMethod(); // error: this.ProtectedMethod(); // memo: 継承したクラスなのでAccess可能 this.ProtectedInternalMethod(); // memo: コンテナ内または継承したクラスなのでAccess可能 this.ProtectedPrivateMethod(); // memo: コンテナ内かつ継承したクラスなのでAccess可能 } } public class Cliant { public void TestAccess() { var server = new Server(); server.PublicMethod(); server.InternalMethod(); //server.PrivateMethod(); // error: //server.ProtectedMethod(); // error: server.ProtectedInternalMethod(); // memo: コンテナ内または継承したクラスなのでAccess可能 //server.ProtectedPrivateMethod(); // error: } } }
ClassLibrary2
using AccessApp; namespace ClassLibrary2 { public class AnotherServer : Server { public void TestAccess() { this.PublicMethod(); //this.InternalMethod(); // error: //this.PrivateMethod(); // error: this.ProtectedMethod(); // memo: 継承したクラスからならAccessできる this.ProtectedInternalMethod(); // memo: コンテナ内または継承したクラスなのでAccess可能 //this.ProtectedPrivateMethod(); // error: } } public class AnotherCliant { public void TestAccess() { var server = new Server(); server.PublicMethod(); //server.InternalMethod(); // error: //server.PrivateMethod(); // error: //server.ProtectedMethod(); // error: //server.ProtectedInternalMethod(); // error: //server.ProtectedPrivateMethod(); // error: } } }