You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:45:13