c# – 允许访问但阻止外部类实例化嵌套类

前端之家收集整理的这篇文章主要介绍了c# – 允许访问但阻止外部类实例化嵌套类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要定义容器类和外部类可访问的嵌套类,但我想控制嵌套类的实例化,这样只有容器类的实例才能创建嵌套类的新实例.

诉讼代码应该有希望证明这一点:

  1. public class Container
  2. {
  3. public class Nested
  4. {
  5. public Nested() { }
  6. }
  7.  
  8. public Nested CreateNested()
  9. {
  10. return new Nested(); // Allow
  11. }
  12. }
  13.  
  14. class External
  15. {
  16. static void Main(string[] args)
  17. {
  18. Container containerObj = new Container();
  19. Container.Nested nestedObj;
  20.  
  21. nestedObj = new Container.Nested(); // Prevent
  22. nestedObj = containerObj.CreateNested(); // Allow
  23.  
  24. }
  25. }

嵌套必须是公共的,以便外部可以访问它.我尝试使用Nested protected构造函数,但是这会阻止Container创建实例,因为Container不是Nested的基类.我可以将Nested的构造函数设置为internal,但我希望阻止所有外部类(包括同一程序集中的那些外部类)访问构造函数.有没有办法做到这一点?

如果无法通过访问修饰符实现这一点,我想知道是否可以在Nested()中抛出异常.但是,我不知道如何测试调用新Nested()的上下文.

解决方法

如何通过接口进行抽象?
  1. public class Container
  2. {
  3. public interface INested
  4. {
  5. /* members here */
  6. }
  7. private class Nested : INested
  8. {
  9. public Nested() { }
  10. }
  11.  
  12. public INested CreateNested()
  13. {
  14. return new Nested(); // Allow
  15. }
  16. }
  17.  
  18. class External
  19. {
  20. static void Main(string[] args)
  21. {
  22. Container containerObj = new Container();
  23. Container.INested nestedObj;
  24.  
  25. nestedObj = new Container.Nested(); // Prevent
  26. nestedObj = containerObj.CreateNested(); // Allow
  27.  
  28. }
  29. }

您也可以使用抽象基类执行相同的操作:

  1. public class Container
  2. {
  3. public abstract class Nested { }
  4. private class NestedImpl : Nested { }
  5. public Nested CreateNested()
  6. {
  7. return new NestedImpl(); // Allow
  8. }
  9. }
  10.  
  11. class External
  12. {
  13. static void Main(string[] args)
  14. {
  15. Container containerObj = new Container();
  16. Container.Nested nestedObj;
  17.  
  18. nestedObj = new Container.Nested(); // Prevent
  19. nestedObj = containerObj.CreateNested(); // Allow
  20.  
  21. }
  22. }

猜你在找的C#相关文章