【问题标题】:C#: Accessing variable from another method, modifying it, returning it to the original methodC#:从另一个方法访问变量,修改它,将它返回到原始方法
【发布时间】:2021-11-28 19:04:20
【问题描述】:

可能是一个非常简单的问题,也许我一开始就没有做对。做了一些研究,但无法理解第二部分。

假设我在 C# 中有两个方法,我想将该变量的值发送到另一个方法。这就是我完成它的方式,将 variable1s 值发送到方法 2

public void methodOne(string variable1)
{
    variable1 = "testing";
    myClass p = new myClass();
    p.methodTwo(variable1);
}
public void methodTwo(string variable1)
{
    Console.Write(variable1);
}

所以这会将 variable1 中的信息从 methodOne 发送到 methodTwo。

但是如果我想修改methodTwo中的变量,然后将它发送回methodOne呢?我会在 methodTwo 中做同样的事情并再次使用它吗?

        myClass p = new myClass();
        p.methodOne(variable1);

我的问题显然是如果我使用该代码,除非我添加中断条件,否则我会陷入来回的无限循环。这让我想,也许我什至没有正确考虑如何做到这一点,而且我错过了一种更简单的方法。

【问题讨论】:

  • 好吧,不知道为什么方法 2 与方法 1 在不同的类中,或者这是否是您想要的,但这就是您想要的。但不管它是否在不同的类中,都传递变量 ByRef。在 Google 上搜索 c# ByRef,看看你想出了什么。
  • 如果您仍然无法弄清楚并且仍然需要帮助,请告诉我。
  • 嗨@David.Warwick,他们在同一个班级,很抱歉造成混乱!我现在将通过参考查找,看看我想出了什么。感谢您的回复!
  • 好吧,我错了,应该是简单的ref,而不是byref。请参阅下面的答案。

标签: c# variables methods


【解决方案1】:

您要做的是使用 ref 关键字传递变量 ByRef。

using System;

namespace ConsoleApp2
{
class Program
{
    static void Main(string[] args)
    {            

        Method1();
    }

    private static void Method1()
    {
        int myVar = 5;
        Console.WriteLine($"myVar in Method1: {myVar}"); // 5

        Method2(ref myVar);

        Console.WriteLine($"myVar in Method2: {myVar}"); // 10
    }

    private static void Method2(ref int AnotherVar)
    {
        AnotherVar = 10;
    }
    
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2021-01-10
    • 2015-01-21
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多