【问题标题】:Should I use static class for storing data?我应该使用静态类来存储数据吗?
【发布时间】:2018-08-21 19:11:51
【问题描述】:

我很难为我的 rpg 游戏存储和访问数据。

现在我需要存储一些经常被访问并且应该是全局的常量。我所做的是创建一个包含所有常量的静态类。

public static class IndexOf
{
    public class Element
    {
        // Element ids in sprite array.
        public const int Water = 0;
        public const int Lava = 1;
        public const int Ice = 2;
    }

    public class Nature
    {
        // Nature (placed on tile)
        public const int Rock = 0;
        public const int Bush = 1;
    }

    public class Biome
    {
        //Biomes ids.
        public const int Mountain = 0;
        public const int River = 1;
    }
}

但是,有没有更好的方法或者这是一个好的解决方案?

【问题讨论】:

标签: c# unity3d


【解决方案1】:

我认为一个更好的(代码将更易读和维护)的选择是切换到enum

  public enum Element {
    Water = 0,
    Lava = 1,
    Ice = 2, 
  };

  public enum Nature {
    Rock = 0,
    Bush = 1,
  };

  public enum Biome {
    Moutain = 0,
    River = 1,
  };

等等。 enum

  1. 更多可读enum 专门设计用于保存常量)
  2. 打字,所以你永远不会犯像int biome = Nature.Rock;这样的错误,因为Biome biome = Nature.Rock;不编译。
  3. 更容易修改(添加一个新项目,比如SandNature

【讨论】:

    【解决方案2】:

    您是否考虑过将常量转换为枚举?

    public enum Element
    {
        // Element ids in sprite array.
        Water,
        Lava,
        Ice
    }
    
    public enum Nature
    {
        // Nature (placed on tile)
        Rock,
        Bush
    }
    
    public enum Biome
    {
        //Biomes ids.
        Mountain,
        River
    }
    

    然后您可以像使用任何枚举(Element.WaterBiome.River 等)一样访问元素。

    【讨论】:

      【解决方案3】:

      对于常量值,您可以查看枚举:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum。 枚举是一组易于阅读且易于扩展的常量整数。

      希望这会有所帮助,如果您需要一个实际示例,请告诉我。

      【讨论】:

        【解决方案4】:

        我在另一个 StackExchange 网站上创建了a very similar question,关于在我的游戏中存储数据的最佳方式是什么。那里有一个非常详细的答案,但简而言之,这是您在游戏中存储数据的选项:

        • 静态脚本
        • 保存数据的游戏对象
        • 播放器首选项
        • 单例模式

        很大程度上取决于您希望如何管理数据、是否要在场景之间停留、您希望读取数据的频率或其他因素。

        没有一种黄金解决方案。您必须分析用例,然后选择最适合您的选项。

        【讨论】:

          猜你喜欢
          • 2021-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多