C#将数组重置为其初始化值?

时间:2016-09-14 17:01:46

标签: c# arrays array-initialization array-initialize

假设我有一系列员工工资,按平均,最高和最低的顺序排列:

import io from IPython.display import display import fileupload def _upload(): _upload_widget = fileupload.FileUploadWidget() def _cb(change): decoded = io.StringIO(change['owner'].data.decode('utf-8')) filename = change['owner'].filename print('Uploaded `{}` ({:.2f} kB)'.format( filename, len(decoded.read()) / 2 **10)) _upload_widget.observe(_cb, names='data') display(_upload_widget) _upload()

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

这只是一个例子,但还有其他一些例子可以方便地重置并返回其初始化内容。在c#中有这个语法吗?

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

1 个答案:

答案 0 :(得分: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);
        }
    }