如何在 C# 中向同一變數分配多個值?\n


如需向同一變數設定多個值,請在 C# 中使用陣列。假設要使用陣列中的一單個變數設定 5 個變數,而不是獲取 5 個變數。

以下就是一個使用字串陣列向單個變數設定三個值的示例 -

string[] arr = new string[3];

現在讓我們對其進行初始化 -

string[] arr = new string[3] {"one", "two", "three"};

以下是一個完整的示例 -

示例

 即時演示

using System;

public class Demo {
   static void Main(string[] args) {

      string[] arr = new string[3] {"one", "two", "three"};

      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine("Values: " + arr[i]);
      }

      Console.ReadKey();
   }

}

輸出

Values: one
Values: two
Values: three

更新於: 2020 年 6 月 20 日

3K+ 瀏覽

啟動您的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.