我想要定义容器类和外部类可访问的嵌套类,但我想控制嵌套类的实例化,这样只有容器类的实例才能创建嵌套类的新实例.
诉讼代码应该有希望证明这一点:
- public class Container
- {
- public class Nested
- {
- public Nested() { }
- }
- public Nested CreateNested()
- {
- return new Nested(); // Allow
- }
- }
- class External
- {
- static void Main(string[] args)
- {
- Container containerObj = new Container();
- Container.Nested nestedObj;
- nestedObj = new Container.Nested(); // Prevent
- nestedObj = containerObj.CreateNested(); // Allow
- }
- }
嵌套必须是公共的,以便外部可以访问它.我尝试使用Nested protected构造函数,但是这会阻止Container创建实例,因为Container不是Nested的基类.我可以将Nested的构造函数设置为internal,但我希望阻止所有外部类(包括同一程序集中的那些外部类)访问构造函数.有没有办法做到这一点?
如果无法通过访问修饰符实现这一点,我想知道是否可以在Nested()中抛出异常.但是,我不知道如何测试调用新Nested()的上下文.
解决方法
如何通过接口进行抽象?
- public class Container
- {
- public interface INested
- {
- /* members here */
- }
- private class Nested : INested
- {
- public Nested() { }
- }
- public INested CreateNested()
- {
- return new Nested(); // Allow
- }
- }
- class External
- {
- static void Main(string[] args)
- {
- Container containerObj = new Container();
- Container.INested nestedObj;
- nestedObj = new Container.Nested(); // Prevent
- nestedObj = containerObj.CreateNested(); // Allow
- }
- }
您也可以使用抽象基类执行相同的操作:
- public class Container
- {
- public abstract class Nested { }
- private class NestedImpl : Nested { }
- public Nested CreateNested()
- {
- return new NestedImpl(); // Allow
- }
- }
- class External
- {
- static void Main(string[] args)
- {
- Container containerObj = new Container();
- Container.Nested nestedObj;
- nestedObj = new Container.Nested(); // Prevent
- nestedObj = containerObj.CreateNested(); // Allow
- }
- }