This question already has answers here:
What do ref, val and out mean on method parameters?
(4 个回答)
2年前关闭。
我将变量保存为一串数据,然后尝试将这些字符串转换回如下变量:
Pop 应该是 345,但返回 0。使用时没有问题
(4 个回答)
2年前关闭。
我将变量保存为一串数据,然后尝试将这些字符串转换回如下变量:
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]
最佳答案
因为 load
是按值传递的,而不是引用(意味着它正在被复制)。使用 ref
或 out
关键字,或仅使用 return
。
void Conv(int i, ref int load)
{...}
...
Conv(3,ref pop);
Check this fiddle 。关于c# - 为什么这个函数不会更新变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55332333/