如何通过泛型初始化数组?

时间:2022-01-06 21:29:34

Is there a way to initialize all elements of an array to a constant value through generics?

有没有办法通过泛型将数组的所有元素初始化为常量值?

3 个解决方案

#1


I would use an extender (.net 3.5 feature)

我会使用扩展器(.net 3.5功能)

public static class Extenders
{
    public static T[] FillWith<T>( this T[] array, T value )
    {
        for(int i = 0; i < array.Length; i++)
        {
            array[i] = value;
        }
        return array;
    }
}

// now you can do this...
int[] array = new int[100];
array.FillWith( 42 );

#2


Personally, I would use a good, old for loop, but if you want a one-liner, here it is:

就个人而言,我会使用一个好的,旧的for循环,但如果你想要一个单行,这里是:

T[] array = Enumerable.Repeat(yourConstValue, 100).ToArray();

#3


If you need to do this often, you can easily write a static method:

如果您经常需要这样做,您可以轻松编写静态方法:

public static T[] FilledArray<T>(T value, int count)
{
    T[] ret = new T[count];
    for (int i=0; i < count; i++)
    {
        ret[i] = value;
    }
    return ret;
}

The nice thing about this is you get type inference:

关于这个的好处是你得到类型推断:

string[] foos = FilledArray("foo", 100);

This is more efficient than the (otherwise neat) Enumerable.Repeat(...).ToArray() answer. The difference won't be much in small cases, but could be significant for larger counts.

这比(否则很整洁)Enumerable.Repeat(...)。ToArray()回答更有效。在小的情况下差异不会太大,但对于更大的计数可能是重要的。

#1


I would use an extender (.net 3.5 feature)

我会使用扩展器(.net 3.5功能)

public static class Extenders
{
    public static T[] FillWith<T>( this T[] array, T value )
    {
        for(int i = 0; i < array.Length; i++)
        {
            array[i] = value;
        }
        return array;
    }
}

// now you can do this...
int[] array = new int[100];
array.FillWith( 42 );

#2


Personally, I would use a good, old for loop, but if you want a one-liner, here it is:

就个人而言,我会使用一个好的,旧的for循环,但如果你想要一个单行,这里是:

T[] array = Enumerable.Repeat(yourConstValue, 100).ToArray();

#3


If you need to do this often, you can easily write a static method:

如果您经常需要这样做,您可以轻松编写静态方法:

public static T[] FilledArray<T>(T value, int count)
{
    T[] ret = new T[count];
    for (int i=0; i < count; i++)
    {
        ret[i] = value;
    }
    return ret;
}

The nice thing about this is you get type inference:

关于这个的好处是你得到类型推断:

string[] foos = FilledArray("foo", 100);

This is more efficient than the (otherwise neat) Enumerable.Repeat(...).ToArray() answer. The difference won't be much in small cases, but could be significant for larger counts.

这比(否则很整洁)Enumerable.Repeat(...)。ToArray()回答更有效。在小的情况下差异不会太大,但对于更大的计数可能是重要的。