C# 数组 - Fill() 方法

C# 数组 Fill() 方法用于将给定的"T"类型的值填充到指定数组的每个元素中。这些元素位于 startIndex(含)到下一个 count 个索引的范围内。

语法

以下是 C# 数组 Fill() 方法的语法 -

public static void Fill<T>(T[] array, T value);
public static void Fill<T>(T[] array, T value, int startIndex, int count);

参数

此方法接受以下参数 -

  • array:待填充的数组。
  • value:应分配给指定数组中每个元素的值。
  • startIndex:表示数组中填充开始的索引。
  • count:要复制的元素数量。

返回值

此方法不返回任何值。

示例 1:填充整个数组

这是 Fill() 方法的基本示例,使用值 10 填充整个数组 -

using System;
class Program
{
   static void Main()
   {
      int[] numbers = new int[5];
      
      Array.Fill(numbers, 10);

      Console.WriteLine(string.Join(", ", numbers));
   }
}

输出

以下是输出 -

10, 10, 10, 10, 10

示例 2:填充数组的部分内容

这是另一个示例,使用重载的 Fill() 方法填充数组的部分内容 -

using System;
class Program
{
   static void Main()
   {
      int[] numbers = new int[10];
      
      Array.Fill(numbers, 7, 2, 5);

      Console.WriteLine(string.Join(", ", numbers));
   }
}

输出

以下是输出 -

0, 0, 7, 7, 7, 7, 7, 0, 0, 0

示例 3:填充字符串数组

让我们看另一个使用 Fill() 方法填充字符串数组的示例 -

using System;
class Program
{
   static void Main()
   {
      string[] fruits = new string[4];
      
      Array.Fill(fruits, "tutorialspoint");
	  
      Console.WriteLine(string.Join(", ", fruits));
   }
}

输出

以下是输出 -

tutorialspoint, tutorialspoint, tutorialspoint, tutorialspoint

示例 4:填充自定义对象数组

以下示例使用 Fill() 方法将自定义对象填充到数组中 -

using System;

class Person
{
   public string Name { 
     get; 
     set; 
   }
   public int Age { 
     get; 
     set; 
   }

   public override string ToString() => $"Name: {Name}, Age: {Age}";
}

class Program
{
   static void Main()
   {
      Person[] people = new Person[2];
      
      // 用默认 Person 填充数组
      Array.Fill(people, new Person { Name = "tutorialspoint India", Age = 10 });

      foreach (var person in people)
      {
         Console.WriteLine(person);
      }
   }
}

输出

以下是输出 -

Name: tutorialspoint India, Age: 10
Name: tutorialspoint India, Age: 10

csharp_array_class.html