如何在C#中限制嵌套类方法仅对其容器类可见?
实现方案
要在C#中达成你的需求,核心是利用嵌套类的访问权限特性:包含嵌套类的外部类(Master)可以访问嵌套类的所有成员(包括private修饰的),而外部其他类仅能访问嵌套类的公共成员。具体实现如下:
非静态版本示例
public class Master { // 公开嵌套类,让外部能访问该类型 public class Input { // 外部可访问的公共属性 public float Horizontal { get; private set; } public float Vertical { get; private set; } // 仅Master可调用的私有方法 private void GetInput() { // 模拟输入逻辑 Horizontal = UnityEngine.Input.GetAxis("Horizontal"); Vertical = UnityEngine.Input.GetAxis("Vertical"); } } private Input _input = new Input(); // Master内部可以直接调用嵌套类的私有方法 public void UpdateInput() { _input.GetInput(); } // 给外部提供访问Input实例的入口 public Input CurrentInput => _input; } // 外部类示例 public class InputController { public void ProcessInput() { Master master = new Master(); // 正常访问嵌套类的公共属性 float horizontal = master.CurrentInput.Horizontal; // 以下代码会编译报错,因为GetInput是私有方法,外部无法访问 // master.CurrentInput.GetInput(); } }
静态版本示例(适合全局场景)
如果需要全局静态逻辑,可调整为静态类结构:
public static class Master { public static class Input { public static float Horizontal { get; private set; } public static float Vertical { get; private set; } private static void GetInput() { Horizontal = UnityEngine.Input.GetAxis("Horizontal"); Vertical = UnityEngine.Input.GetAxis("Vertical"); } } public static void UpdateGlobalInput() { // Master静态类可直接调用嵌套静态类的私有方法 Input.GetInput(); } } public class InputController { public void ProcessStaticInput() { // 访问静态嵌套类的公共属性 float vertical = Master.Input.Vertical; // 编译报错,私有方法无法被外部访问 // Master.Input.GetInput(); } }
关键原理
- 嵌套类设为
public:确保外部类能识别并使用该类型。 - 嵌套类的属性设为
public:允许外部类读取(如果需要外部修改可调整setter权限)。 - 嵌套类的方法设为
private:仅包含它的Master类可以调用,外部类完全不可见。
之前尝试静态类、命名空间未成功的原因:
- 静态类如果把方法设为
public,外部必然能调用; - 命名空间下的类成员访问控制基于程序集(如
internal),无法限定仅某个特定类可调用方法; - 错误使用访问修饰符(比如用
protected而非private,或未正确控制嵌套类的访问级别)。
内容的提问来源于stack exchange,提问作者Guilherme_F
相关产品推荐
相关产品推荐

