简短的回答是没有内置的方法可以做到这一点。该框架不会自动为您跟踪数组的初始状态,只会跟踪其当前状态,因此它无法知道如何将其重新初始化为原始状态。不过你可以手动完成。确切的方法取决于您的数组最初初始化的内容:
// Array will obviously contain {1, 2, 3}
int[] someRandomArray = { 1, 2, 3 };
// Won't compile
someRandomArray = { 1, 2, 3 };
// We can build a completely new array with the initial values
someRandomArray = new int[] { 1, 2, 3 };
// We could also write a generic extension method to restore everything to its default value
someRandomArray.ResetArray();
// Will be an array of length 3 where all values are 0 (the default value for the int type)
someRandomArray = new int[3];
ResetArray 扩展方法如下:
// The <T> is to make T a generic type
public static void ResetArray<T>(this T[] array)
{
for (int i = 0; i < array.Length; i++)
{
// default(T) will return the default value for whatever type T is
// For example, if T is an int, default(T) would return 0
array[i] = default(T);
}
}