如何在 C# 中使用 array 類的 SetValue(,) 方法?


SetValue() 方法設定一維 Array 中指定位置處的元素值。索引指定為一個 32 位整數。

首先,設定陣列。

Array arr = Array.CreateInstance(typeof(String), 6);

不使用 SetValue() 方法為元素設定值。

arr.SetValue("One", 0);
arr.SetValue("Two", 1);
arr.SetValue("Three", 3);
arr.SetValue("Four", 4);
arr.SetValue("Five", 5);

以下是一個顯示在 C# 中使用 SetValue() 方法的示例。

示例

 線上演示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 6);
         arr.SetValue("One", 0);
         arr.SetValue("Two", 1);
         arr.SetValue("Three", 3);
         arr.SetValue("Four", 4);
         arr.SetValue("Five", 5);
         Console.WriteLine("Length {0}",arr.GetLength(0).ToString());
         Console.ReadLine();
      }
   }
}

輸出

Length 6

更新日期:2020 年 6 月 23 日

1K+ 次瀏覽

開啟您的 職業生涯

透過完成本課程獲得認證

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