如何限制C#嵌套类构造函数对外访问且保留静态方法对外可见
解决方案
核心利用C#外层类可访问嵌套类所有私有成员的语言特性,通过嵌套类的访问修饰符控制实现所有需求,修改后完整代码如下:
public class FooMaster { // 私有抽象基类,外部完全不可见 private abstract class FooChildBase { internal abstract string Text1 { get; } } // 公开嵌套类,外部可见可直接访问公共静态方法 public class FooChild1 : FooChildBase { // 私有构造函数,仅外层FooMaster可实例化 private FooChild1() { } internal override string Text1 { get; } = "Test"; public static void Test() { //Do something } } public class FooChild2 : FooChildBase { private FooChild2() { } internal override string Text1 { get; } = "Test"; } private static FooChildBase GetFooChild(int number) { return number switch { 1 => new FooChild1(), 2 => new FooChild2(), _ => throw new NotImplementedException("...") }; } public static string GetFooChildText1Value(int number) { FooChildBase fooChild = GetFooChild(number); return fooChild?.Text1 ?? throw new NullReferenceException("..."); } }
需求匹配验证
- FooMaster之外的类仅可通过调用
GetFooChildText1Value获取Text1的值:私有基类FooChildBase对外完全不可见,外部无法获取该类型的实例引用,自然无法直接访问Text1属性,仅能通过公共方法获取返回值。 - FooMaster内部可正常访问FooChild1、FooChild2的属性和构造函数:C#语言规则支持外层类访问嵌套类的所有私有成员,私有构造、internal属性都可正常访问。
- 无法从FooMaster外部调用FooChild1或FooChild2的构造函数:两个子类的构造函数均为私有,仅外层类可调用。
- FooMaster外部无法查看FooChild1或FooChild2的Text1属性:该属性重写自私有基类的internal抽象属性,对外部完全不可见。
- FooChild1和FooChild2类型对外可见,可直接调用公共静态方法:两个子类均为public嵌套类,外部可直接通过
FooMaster.FooChild1.Test()的形式调用静态方法,无需额外编写中转方法。
内容的提问来源于stack exchange,提问作者Max N
相关产品推荐
相关产品推荐

