C# Simple 相当于 Enum 但具有多种数据类型?

标签 c#

对于公共(public)预定义数据源是否有更好的解决方案,该数据源可以是全局的,位于像Enum这样的命名空间中,无需使用构造函数即可轻松访问,但可以像小型数据库一样保存多种数据类型。 到目前为止我最好的方法是:

 public class PublicData
    {

        int[] Values = { 89, 11, 4, 12, 4, 24, 12 };

        string[] Names = { "item1", "item2", "item3", "item4", "item5", "item6", "item7" };

        bool[] Logics = { true, true, false, false, false, true, true };

        public int GetValue(int i)
        {
            return Values[i];
        }

        public string GetName(int i)
        {
            return Names[i];
        }

        public bool GetLogic(int i)
        {
            return Logics[i];
        }

    }

最简单的使用方法是:

TextBox.Text = new PublicData.GetName(intReference);
CheckBox.Checked = new PublicData.GetLogic(intReference);

但我仍然想知道是否有更好的方法,例如 Enums,它更轻且不需要任何构造函数。

最佳答案

我自己不会尽可能长时间地使用它,因为它会使单元测试变得更加困难:如果将类设为静态,则不需要 new 关键字。

public static class PublicData {
    private static readonly int[] Values = { 89, 11, 4, 12, 4, 24, 12 };
    private static readonly string[] Names = { "item1", "item2", "item3", "item4", "item5", "item6", "item7" };
    private static readonly bool[] Logics = { true, true, false, false, false, true, true };

    public static int GetValue(int i) { return Values[i]; }
    public static string GetName(int i) { return Names[i]; }
    public static bool GetLogic(int i ) { return Logics[i]; }
}

用法相同,但不需要 new 关键字,正如我已经提到的。

关于C# Simple 相当于 Enum 但具有多种数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76596114/

相关文章:

c# - 数据不显示在 Text={Binding} 上?

c# - UI图像长度与图片长度

c# - 使用反射从程序集加载时的不同类型

c# - 根据使用 imap 的验证程序,远程证书无效

c# - 使用 string.format 将空格插入字符串

c# - 从 ASP.NET Core 2.0 中的类库访问当前上下文的推荐方法?

c# - 在 C# 中从 AD 获取主组名的最简单方法是什么?

c# - Entity Framework 获取缓慢

c# - 异步方法未按正确(预期)顺序执行

c# - c#和asp.net/c#的区别