gpt4 book ai didi

c# - 在 C# 中定义常量

转载 作者:行者123 更新时间:2023-11-30 05:04:01 26 4
gpt4 key购买 nike

我是 C/C++ 到 C# 开发人员。

我需要做如下的事情,

#define LEN 20
int data[LEN];

由于 C# 不支持 #define,许多论坛建议声明一个 const 变量。 const 变量可能对下面的内容有帮助,但对上面的内容没有帮助。

for (int a = 0; a < LEN; a++)
{
x += data[LEN - a - 1];
}

那么,我该如何将常量用于数组声明呢?

最佳答案

C# 允许您创建多种内置类型的常量 using const keyword .

Constants can be numbers, Boolean values, strings, or a null reference.

这是一个小例子:

public class Demo {

public const int Length = 20;

public void Main(string[] args) {
var data = new int[Length];
for (var i = 0 ; i != Length ; i++) {
data[i] = 2*i + 3;
}
}

}

注意: C# naming guidelines建议避免全大写命名。

关于c# - 在 C# 中定义常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49132072/

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