c# - 在方法中重写时的数组参数不会在其外部更改

标签 c# .net

我有一个方法,它的参数是字符串数组。在函数中我用另一个数组覆盖它时它不会在它之外改变(如果我理解正确的话数组是通过引用传递的)。

我有一个看起来像这样的方法:

    static void Method(string word, string[] tab)
    {
        string [] tab1;
        [..] 

        tab = tab1; // tab changes to tab1
    }

     static void Main(string[] args)
    {
         string[]  tab = { "", "", "", "", "", "", "", "", "", "" };
         Method("443", tab);
         //and here tab does not change like I though it would.
     }

最佳答案

更好的设计应该是:

static string[] Method(string word, string[] tab)
{
    string [] tab1;
    [..] 

    return tab1;
}

static void Main(string[] args)
{
     string[] tab = { "", "", "", "", "", "", "", "", "", "" };
     tab = Method("443", tab);
}

关于c# - 在方法中重写时的数组参数不会在其外部更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42841938/

相关文章:

c# - Spring AOP + MVVM基础+ PropertyChanged

c# - 发布时更改 Visual Studio 中的连接字符串

c# - 是什么导致 EF 插入比普通 ADO.NET 慢得多?

c# - 在C#.NET中,如何给HTML、CSS等静态文件引用添加版本号?

c# - WCF 中的 IMetadataExchange 问题

c# - 使用来自其他库的值的 Swig 枚举

c# - 如何访问 PropertyChanged 事件的订阅者?

c# - 属性 'Text' 上的 ContentPropertyAttribute 无效

c# - 完全像 Javascript 的异步 C# 应用程序

c# - SslStream.DataAvailable 不是有效函数