C# 中的 Redim 保留?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/327916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:21:37  来源:igfitidea点击:

Redim Preserve in C#?

c#arrays

提问by JL.

I was shocked to find out today that C# does not support dynamic sized arrays. How then does a VB.NETdeveloper used to using ReDim Preservedeal with this in C#?

今天我震惊地发现 C# 不支持动态大小的数组。那么习惯于使用ReDim PreserveVB.NET开发人员如何在 C# 中处理这个问题?

At the beginning of the function I am not sure of the upper bound of the array. This depends on the rows returned from the database.

在函数开始时,我不确定数组的上限。这取决于从数据库返回的行。

采纳答案by Michael L

Use ArrayLists or Generics instead

改用 ArrayLists 或泛型

回答by driis

Use a List<T>. It will dynamically size as needed.

使用 List<T>。它将根据需要动态调整大小。

回答by Jonathan Allen

You really shouldn't be using ReDim, it can be every expensive. I prefer List(Of T), but there are many options in this area.

你真的不应该使用 ReDim,它可能非常昂贵。我更喜欢 List(Of T),但在这方面有很多选择。

That said, you had a question and here is your answer.

也就是说,你有一个问题,这是你的答案。

x = (int[]) Utils.CopyArray((Array) x, new int[10]);

回答by Jon Skeet

VB.NET doesn't have the idea of dynamically sized arrays, either - the CLR doesn't support it.

VB.NET 也没有动态大小数组的想法——CLR 不支持它。

The equivalent of "Redim Preserve" is Array.Resize<T>- but you mustbe aware that if there are other references to the original array, they won't be changed at all. For example:

“Redim Preserve”的等价物是Array.Resize<T>- 但您必须注意,如果有其他对原始数组的引用,它们根本不会被更改。例如:

using System;

class Foo
{
    static void Main()
    {
        string[] x = new string[10];
        string[] y = x;

        Array.Resize(ref x, 20);
        Console.WriteLine(x.Length); // Prints out 20
        Console.WriteLine(y.Length); // Still prints out 10
    }
}

Proof that this is the equivalent of Redim Preserve:

证明这相当于 Redim Preserve:

Imports System

Class Foo
    Shared Sub Main()
        Dim x(9) as String
        Dim y as String() = x

        Redim Preserve x(19)
        Console.WriteLine(x.Length)
        Console.WriteLine(y.Length)
    End Sub
End Class

The two programs are equivalent.

这两个程序是等价的。

If you truly want a dynamically sized collection, you should use List<T>(or something similar). There are various issues with using arrays directly - see Eric Lippert's blog postfor details. That's not to say you should always avoid them, by any means - but you need to know what you're dealing with.

如果你真的想要一个动态大小的集合,你应该使用List<T>(或类似的东西)。直接使用数组存在各种问题 -有关详细信息,请参阅Eric Lippert 的博客文章。这并不是说你应该总是避免它们,无论如何——但你需要知道你在处理什么。

回答by Hameer Abbasi

I couldn't help but notice that noneof the above answers approach the concept of multidimensional arrays. That being said, here's an example. The array in question is predefined as x.

我不禁注意到上述答案都没有接近多维数组的概念。话虽如此,这是一个例子。有问题的数组被预定义为x

int[,] temp = new int[newRows, newCols];
int minRows = Math.Min(newRows, x.GetUpperBound(0) + 1);
int minCols = Math.Min(newCols, x.GetUpperBound(1) + 1);
for (int i = 0; i < minRows ; ++i)
     for (int j = 0; j < minCols; ++j)
         temp[i, j] = x[i, j];
x = temp;

回答by Tete1805

Just for fun, here's one way to use generics in order to redim/extend a unidimensional array (add one more "row") :

只是为了好玩,这里有一种使用泛型来重新定义/扩展一维数组(再添加一个“行”)的方法:

static T[] Redim<T>(T[] arr, bool preserved)
{
    int arrLength = arr.Length;
    T[] arrRedimed = new T[arrLength + 1];
    if (preserved)
    {
        for (int i = 0; i < arrLength; i++)
        {
            arrRedimed[i] = arr[i];
        }
    }
    return arrRedimed;
}

And one to add n rows (though this doesn't prevent user from undersizing the array, which will throw an error in the for loop) :

还有一个添加 n 行(尽管这不会阻止用户缩小数组的大小,这会在 for 循环中引发错误):

static T[] Redim<T>(T[] arr, bool preserved, int nbRows)
{
    T[] arrRedimed = new T[nbRows];
    if (preserved)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arrRedimed[i] = arr[i];
        }
    }
    return arrRedimed;
}

I'm sure you get the idea.

我相信你明白了。

For a multidimensional array (two dimensions), here's one possibility:

对于多维数组(二维),这是一种可能性:

static T[,] Redim<T>(T[,] arr, bool preserved)
{
    int Ubound0 = arr.GetUpperBound(0);
    int Ubound1 = arr.GetUpperBound(1);
    T[,] arrRedimed = new T[Ubound0 + 1, Ubound1];
    if (preserved)
    {
        for (int j = 0; j < Ubound1; j++)
        {
            for (int i = 0; i < Ubound0; i++)
            {
                arrRedimed[i, j] = arr[i, j];
            }
        }
    }
    return arrRedimed;
}

In your program, use this with or even without the type specified, the compiler will recognize it :

在您的程序中,无论是否指定类型都可以使用它,编译器会识别它:

int[] myArr = new int[10];
myArr = Redim<int>(myArr, true);

or

或者

int[] myArr = new int[10];
myArr = Redim(myArr, true);

Not sure if all this is really relevant though. =D Please feel free to correct me or improve my code. ;)

不确定所有这些是否真的相关。=D 请随时纠正我或改进我的代码。;)

回答by AllDayPiano

Even though it's a long time ago it might help someone looking for a simple solution - I found something great in another forum:

即使是很久以前,它也可能会帮助寻找简单解决方案的人 - 我在另一个论坛中发现了一些很棒的东西:

//from Applied Microsoft.NET framework Programming - Jeffrey Richter
public static Array RedimPreserve(Array origArray, Int32 desiredSize)
        {
            System.Type t = origArray.GetType().GetElementType();
            Array newArray = Array.CreateInstance(t, desiredSize);
            Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize));
            return newArray;
        }

Source: https://social.msdn.microsoft.com/Forums/en-US/6759816b-d525-4752-a3c8-9eb5f4a5b194/redim-in-c?forum=csharplanguage

来源:https: //social.msdn.microsoft.com/Forums/en-US/6759816b-d525-4752-a3c8-9eb5f4a5b194/redim-in-c?forum=csharplanguage