在 C# 中声明一个常量数组

Muhammad Maisam Abbas 2024年2月16日
在 C# 中声明一个常量数组

本教程将讨论在 C# 中声明常量数组的方法。

在 C# 中使用 readonly 关键字声明一个常量数组

在 C# 中,我们无法使用以下语法声明常量数组。

public const string[] Values = { "Value1", "Value2", "Value3", "Value4" };

这将导致编译器错误,因为 const 关键字用于编译时已知的值。但是数组在编译时不会初始化,因此在编译时不知道数组的值。

通过在 C# 中使用 readonly 关键字可以避免此错误。readonly 关键字用于指定初始化后不能修改变量的值。以下代码示例向我们展示了如何在 C# 中使用 readonly 关键字声明常量数组。

using System;

namespace constant_array {
  class Program {
    public static readonly string[] Values = { "Value1", "Value2", "Value3" };
    static void Main(string[] args) {
      foreach (var Value in Values) {
        Console.WriteLine(Value);
      }
    }
  }
}

输出:

Value1
Value2
Value3

在上面的代码中,我们在 C# 中使用 readonly 关键字声明了常量数组 Values

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相关文章 - Csharp Array