在函数中调整了数组的大小,但当它返回时,它是原始大小

问题描述 投票:0回答:1

我将一个数组传递到一个单独的 cs 文件中的函数中,在其中调整数组的大小。当我返回数组并在主文件中检查其长度时,它是之前的大小。我完全不知道该怎么办。

    //this is the code in my main file
    string[] Names = new string[0];

    selectCode.namesSetup(Names);

    //and this is the code in my file where the function is located
    public string[] namesSetup(string[] Names)
    {
        Array.Clear(Names, 0, Names.Length);
        Array.Resize(ref Names, 65);

        return Names;
    }
c# .net
1个回答
0
投票

您实际上无法调整数组的大小。数组是固定大小的。该

Array.Resize
方法实际上创建了一个指定大小的新数组,并将元素从旧数组复制到新数组。这就是为什么第一个参数被声明为
ref
:因为它需要引用一个与传入不同的对象。因为你自己的
namesSetup
中的参数没有被声明为
ref
,所以在方法对您传入的变量没有影响。

问题是,您的方法实际上返回新数组,但您忽略了返回值。只需执行以下操作,您的代码就可以在不更改该方法的情况下工作:

Names = selectCode.namesSetup(Names);

或者,您可以将方法更改为:

public void namesSetup(ref string[] Names)
{
    Array.Clear(Names, 0, Names.Length);
    Array.Resize(ref Names, 65);
}

然后这样称呼它:

selectCode.namesSetup(ref Names);
© www.soinside.com 2019 - 2024. All rights reserved.