0

假设我有一组按平均、最大值和最小值排列的员工工资:

int[] wages = {0, 0, Int32.MaxValue};

上面的代码已初始化,因此当我找到最大值时,我可以与 0 进行比较,任何高于现有值的东西都会击败它并替换它。所以 0 在这里工作正常。查看最小值,如果我将其设置为 0,我会遇到问题。比较工资(都大于 0)并用最低工资代替最低工资是不可能的,因为没有一个工资会低于 0 值。所以我使用了 Int32.MaxValue,因为它保证每个工资都低于这个值。

这只是一个示例,但还有其他示例可以方便地重置和排列回其初始化内容。c# 中是否有这方面的语法?

编辑:@Shannon Holsinger 找到了答案: wages = new int[] {0, 0, Int32.MaxValue};

4

1 回答 1

0

简短的回答是没有内置的方法可以做到这一点。该框架不会自动为您跟踪数组的初始状态,只会跟踪其当前状态,因此它无法知道如何将其重新初始化为原始状态。不过你可以手动完成。确切的方法取决于您的数组最初初始化的内容:

        // 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);
        }
    }
于 2016-09-14T17:23:31.673 回答