Visibility of nested class constructor

后端 未结 6 900
渐次进展
渐次进展 2021-02-13 18:41

Is there a way to limit the instantiation of the nested class in C#? I want to prevent nested class being instantiated from any other class except the nesting class, but to allo

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 19:24

    Since there is nothing in C# syntax you'll have to implement something like "a contract" between them. You can take advantage of the fact that nested class can access private fields of its parent:

    public class ParentClass
    {
      private static Func _friendContract;
    
      public class FriendClass
      {
          static FriendClass()
          {
              _friendContract= () => new FriendClass();
          }
    
          private FriendClass() { }
      }
    
      ///Usage
      public FriendClass MethodUse()
      {
          var fInstance = _friendContract();
          //fInstance.DoSomething();
          return fInstance;
      }
    }
    

    Of course you can adjust the contract to handle different parameters

     private static Func _friendContract;
    

提交回复
热议问题