在 C# 中,动态初始化数组意味着在程序运行时根据需要为数组分配内存并设置值,而不是在编译时固定大小和内容。这通常用于场景中数组的大小或内容在运行时才能确定。
动态初始化数组的方法
1. 动态设置大小
在运行时确定数组的大小后,使用 new 关键字动态初始化数组。
示例:
using System;
class Program
{
static void Main()
{
Console.Write("Enter the size of the array: ");
int size = int.Parse(Console.ReadLine());
int[] numbers = new int[size]; // 动态设置数组大小
for (int i = 0; i < size; i++)
{
Console.Write($"Enter value for element {i}: ");
numbers[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Array elements are:");
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
2. 动态初始化二维数组
动态初始化多维数组,尤其是二维数组时,大小可以在运行时确定。
示例:
using System;
class Program
{
static void Main()
{
Console.Write("Enter the number of rows: ");
int rows = int.Parse(Console.ReadLine());
Console.Write("Enter the number of columns: ");
int columns = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, columns]; // 动态设置二维数组大小
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write($"Enter value for matrix[{i},{j}]: ");
matrix[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Matrix elements are:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
}
3. 动态初始化交错数组
交错数组(Jagged Array)是数组的数组,每个子数组可以有不同的长度。
示例:
using System;
class Program
{
static void Main()
{
Console.Write("Enter the number of rows for the jagged array: ");
int rows = int.Parse(Console.ReadLine());
int[][] jaggedArray = new int[rows][]; // 动态设置交错数组的行数
for (int i = 0; i < rows; i++)
{
Console.Write($"Enter the size of row {i}: ");
int size = int.Parse(Console.ReadLine());
jaggedArray[i] = new int[size]; // 为每行分配不同大小
for (int j = 0; j < size; j++)
{
Console.Write($"Enter value for jaggedArray[{i}][{j}]: ");
jaggedArray[i][j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Jagged Array elements are:");
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Row " + i + ": ");
foreach (int value in jaggedArray[i])
{
Console.Write(value + " ");
}
Console.WriteLine();
}
}
}
4. 使用动态数据填充数组
有时数组的内容依赖于动态数据(例如用户输入或其他方法返回的值)。
示例:
using System;
class Program
{
static void Main()
{
string[] names;
Console.Write("Enter the number of names you want to store: ");
int count = int.Parse(Console.ReadLine());
names = new string[count]; // 动态设置字符串数组大小
for (int i = 0; i < count; i++)
{
Console.Write($"Enter name {i + 1}: ");
names[i] = Console.ReadLine();
}
Console.WriteLine("Stored names are:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
总结
动态初始化数组在 C# 中非常灵活,可以通过以下方式实现:
- 动态分配大小。
- 动态填充值。
- 动态设置多维数组或交错数组。
这些方法适用于数组大小和内容在运行时才能确定的场景,例如用户输入或根据程序逻辑分配数组。
2023

被折叠的 条评论
为什么被折叠?



