gpt4 book ai didi

c# - 顺序常量字段值

转载 作者:行者123 更新时间:2023-11-30 14:50:18 26 4
gpt4 key购买 nike

我有这样的类(class)

class MyClass{
const int Item1 = 1;
const int Item2 = 2;
const int Item3 = 3;
...
}
class MySecondClass : MyClass
{
const int Item1 = 4;
const int Item2 = 5;
const int Item3 = 6;
...
}

是否有一种自动设置这些值以确保它们是顺序的并且仍然是常量的方法?我们在两个开发人员添加一个项目的合并中遇到了问题,我们最终得到两个具有相同值的项目。

目前,我们检查单元测试是否会发生这种情况,并在测试失败时修复它。但在编译期间我们可以做这样的事情会更好:

int i=0;
class MyClass{
const int Item1 = i;
const int Item2 = ++i;
const int Item3 = ++i;
...
}
class MySecondClass : MyClass{
const int Item4 = ++i;
const int Item5 = ++i;
const int Item6 = ++i;
...
}

编辑:这是许多类中的遗留代码,我无法将结构更改为枚举。

最佳答案

class A
{
static A() { }

protected static int i = 0;

public static readonly int Item1 = i++;
public static readonly int Item2 = i++;
public static readonly int Item3 = i++;

}

class B : A
{
static B() { }

public static readonly int Item4 = i++;
public static readonly int Item5 = i++;
public static readonly int Item6 = i++;
}

不能使用 const 因为 i++ 不被认为是常量表达式,但是 static readonly 是一个类似的约束。

根据 10.4.5.1,有必要显式包含静态构造函数以继承静态构造函数的初始化顺序规则。

根据 10.11 :

If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.

和:

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class is created.
  • Any of the static members of the class are referenced.

因为B引用了A的静态成员i,所以A的静态构造函数必须先执行。因此,你应该保证(如果我已经正确地解释了这一切)Item1 == 0, …, Item6 == 5 provided that 没有其他后代>A 也改变了 i

如果您将另一个后代 C 添加到 A,那么您需要从 C 引用 B 的静态字段> 如果您想在 C 之前订购 B(反之亦然)。


旧答案(问题更改前)

枚举怎么样?

enum Items : int
{
Item1 = 1,
Item2,
Item3,
// …
}

您可以取回您的整数:

var x = (int)Items.Item1;

关于c# - 顺序常量字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36957191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com