c# - 为什么这个函数不更新变量?

标签 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]

最佳答案

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

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

...

Conv(3,ref pop);

Check this fiddle .

关于c# - 为什么这个函数不更新变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332333/

相关文章:

c# - C# 与 C 函数互操作的性能损失

c# - 如何使用 .Net Core 在 Linux 上从同一网络的远程计算机获取 mac 地址

c# - 需要遍历一个解决方案中的.cs文件,判断是否使用了某个函数

c# - 我可以创建一个继承自强类型 DataRow 的自定义类吗?

c# - WPF - FindName 在不应返回 null 时返回

Java 相当于 C# ExpandoObject

c# - 如何在 C# 中将模式与正则表达式匹配,以应对正则表达式的挑战?

C# MySQL 执行 UPDATE 什么都不做

c# - 已编辑行的自定义样式 GridView ASP.NET

c# - 从 .txt 文件读取时如何指示空格