在 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