C# 如何构造常量值

C# 如何构造常量值,c#,C#,我想组织一组常量 方法1: class Constants { public const int A_B_C = 1; public const string A_B_D = "test"; } var x = Constants.A_B_D; 方法2: class Constants { public static readonly A A = new A(); } class A { public static readonly B B

我想组织一组常量

方法1:

class Constants
{
    public const int A_B_C = 1;
    public const string A_B_D = "test";
}
var x = Constants.A_B_D;
方法2:

class Constants
{
    public static readonly A A = new A();
}
class A
{
    public static readonly B B = new B();
}
class B
{
    public static const int C = 1;
    public static const string D = "test";
}
var x = Constants.A.B.D;
我想知道。。。有没有办法简化方法2,减少代码。。。?一些语法糖来声明它像JSON或类似的东西

伪代码:

class Constants
{
    public static readonly [datatype] A =
    {
        public static readonly [datatype] B =
        {
            public const int C = 1;
            public const string D = "test";
        };
    };
}
看起来嵌套类符合以下条件:

namespace Constants
{
    public static class A
    {
        public static class B
        {
            public const int C = 1;

            public const string D = "test";
        }
    }
}

因为它们都是常量,我不明白为什么你需要成为类。您可以使用struct而不必依赖于静态

namespace Constants
{
    public struct A
    {
        public struct  B
        {
            public const int C = 1;

            public const string D = "test";
        }
    }
}
这样称呼它

var c = Constants.A.B.C;

为什么要创建一个只包含静态/常量成员的B实例?你可以在没有任何实例的情况下访问这些类类可以包含类…我的意思是,你可以只做静态类常量{static class A{static class B{const int C=1;const string D=test;}}}}}}如果你想的话…也许只需要使用一个JSON文件并读/写它你对这些类的看法是正确的。这就是我问是否有更简单的方法来声明常量的原因。使用您的解决方案,有人可以用新的A.B创建一个B的实例,所以我想我应该使用嵌套的staticclasses@Michael事实上,你可以这么做,你为什么要这么做?结构是空的。为什么使用结构比使用类更好?@KlausGütter在这种特定情况下,我看到的唯一区别是内存占用。使用struct时应小128位。但这取决于你使用了多少类。现在只使用了2个指针,所以我假设2个额外的64位指针静态类应该没有开销。