简体   繁体   English

C# 中的 Redim Preserve?

[英]Redim Preserve in C#?

I was shocked to find out today that C# does not support dynamic sized arrays.今天我震惊地发现 C# 不支持动态大小的数组。 How then does a VB.NET developer used to using ReDim Preserve deal with this in 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.这取决于从数据库返回的行。

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 must be aware that if there are other references to the original array, they won't be changed at all. “Redim Preserve”的等价物是Array.Resize<T> - 但您必须注意,如果有其他对原始数组的引用,它们根本不会被更改。 For example:例如:

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).如果你真的想要一个动态大小的集合,你应该使用List<T> (或类似的东西)。 There are various issues with using arrays directly - see Eric Lippert's blog post for details.直接使用数组存在各种问题 - 有关详细信息,请参阅Eric Lippert 的博客文章 That's not to say you should always avoid them, by any means - but you need to know what you're dealing with.这并不是说无论如何你都应该避免它们——但你需要知道你在处理什么。

改用 ArrayLists 或泛型

Use a List<T>.使用列表<T>。 It will dynamically size as needed.它将根据需要动态调整大小。

You really shouldn't be using ReDim, it can be very expensive.你真的不应该使用 ReDim,它可能非常昂贵。 I prefer List(Of T), but there are many options in this area.我更喜欢 List(Of T),但是这方面有很多选择。

That said, you had a question and here is your answer.也就是说,你有一个问题,这是你的答案。

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

I couldn't help but notice that none of 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;

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 请随时纠正我或改进我的代码。 ;) ;)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM