C# Array initialization - with non-default value

前端 未结 6 1828
温柔的废话
温柔的废话 2020-12-08 20:03

What is the slickest way to initialize an array of dynamic size in C# that you know of?

This is the best I could come up with

private bool[] GetPageN         


        
6条回答
  •  -上瘾入骨i
    2020-12-08 20:21

    Many times you'd want to initialize different cells with different values:

    public static void Init(this T[] arr, Func factory)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = factory(i);
        }
    }
    

    Or in the factory flavor:

    public static T[] GenerateInitializedArray(int size, Func factory)
    {
        var arr = new T[size];
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = factory(i);
        }
        return arr;
    }
    

提交回复
热议问题