为什么此函数不更新变量?

时间:2019-03-25 06:33:21

标签: c#

我将变量保存到数据字符串中,然后尝试将这些字符串转换回如下所示的变量:

using System;

public class Program
{
    static int pop;
    static string[] log = new string[10];
    public static void Main()
    {
       string abc = "5 6 10 345 23 45";
       log = abc.Split(' ');
       Conv(3,pop);
       Console.WriteLine(pop); // expected result: pop == 345
    }
    static void Conv(int i, int load)
    {
       if (log[i] != null){ load = int.Parse(log[i]);}
    }
}

Pop应该为345,但应返回0。使用时没有问题 pop = int.Parse.log[i]

2 个答案:

答案 0 :(得分:4)

因为load是通过 value 传递的,而不是通过 reference 传递的(意味着它已被复制)。使用refout关键字,或仅使用return

void Conv(int i, ref int load)
{...}

...

Conv(3,ref pop);

check this fiddle

答案 1 :(得分:3)

尽管Michael的答案肯定是正确的,但获得您所期望的另一种方法是更改​​Conv的实现以返回值,而不是使用按引用传递。

public static void Main()
{
    string abc = "5 6 10 345 23 45";
    log = abc.Split(' ');
    int newPop = Conv(3,pop);
    Console.WriteLine(newPop);
}

static int Conv(int i, int load)
{
    if (log[i] != null)
    {
        return int.Parse(log[i]);
    }

    return load;
}

或稍作重构:

static int Conv(int i, int load)
{
    string entry = log[i];
    return entry == null
        ? load 
        : int.Parse(entry);
}
相关问题