【问题标题】:OOP how to do Class "folders"OOP如何做类“文件夹”
【发布时间】:2023-03-23 00:56:02
【问题描述】:

我想做的是:

一些脚本访问:

//...
string Str = "aab";

void Update(){
    GUI3D.Label(Str);
    GUI3D.TextField(ref Str);
}
//...

在 GUI3D 脚本中:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class GUI3D {
    static void Label(string Text){
        // make text apear
    }
    static int CursorField;
    static void TextField(ref string Text){
        // changing cursor field depending on the inputs
        // change text and make it apear
    }
}

我希望我没有减少太多。 但我想要做的是只有 TextField 可以访问 CursorField 而没有其他人。

如果我想做的话:

    static void Label(string Text){
        // make text apear
        CursorField = 0; // that I'd get error due to protection level.
    }

我该怎么做?

【问题讨论】:

    标签: c# class oop unity3d


    【解决方案1】:

    您遇到了架构问题。您不能对自己隐藏班级成员。你是在告诉你的静态 GUI3D 类给 Label() 一些东西,你还试图对自己隐藏数据?为什么需要对 GUI3D 类的一个成员函数隐藏数据?

    【讨论】:

    • 就像我说的我会创建一个 GUI3D 可访问的子函数但它的成员是私有的,为什么我需要隐藏它,因为我的 3D gui 已经有 600 行长并且它开始有点令人困惑。我也不关心我是否必须改变架构,这就是我问这个问题的原因。
    【解决方案2】:

    如果你不介意稍微改变你的架构,你可以试试这样的类(请原谅语法错误,我手边没有编译器:D):

    public class MyLabel {
        private string _text;
        public string Text {
            get { return _text; }
            set { _text = value; CursorField = _text.Length; }
        }
    
        public int CursorField { get; private set; }
    }
    

    正如 baoghal 所说,你不能对自己隐藏一个类成员 - 所以将该功能包装在一个辅助类中并只让该类本身修改 CursorField。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多