【问题标题】:Access a Variable Inside a Function [duplicate]访问函数内的变量[重复]
【发布时间】:2020-06-16 11:30:34
【问题描述】:

[在此处输入图片描述][1]

我如何才能访问(例如,注释 Console.WriteLine())函数内的变量? 试图在主函数中声明它(在 2 个注释位置),但它说它未使用。 谢谢!

    public void Form1_Load_1(object sender, EventArgs e)
    {
     //string filename = “ “;
        try
        {   
            //string filename = “ “;
            rename("02-66977V2", "X");
            //Console.WriteLine(filename);


        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.ToString());
        }
        finally
        {
        }

    }

    public void rename(string Number, string Type)
    {
        string filename = " ";

        try
        {
            if (Number.Contains("V2"))
            {
                filename = Number + Type;
            }
        }

        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.ToString());
        }
        finally
        {
        }
    }

【问题讨论】:

  • 你不能(你可以,但是通过全局变量或参数,而不是“函数到函数”)。您需要研究“范围”。
  • 在你的函数rename中将rename签名更改为public string rename和return filename。您的实际问题可能是“如何获得函数的结果”。
  • 谢谢大家,我会看看前面的问题。

标签: c# variables


【解决方案1】:

我假设您的实际问题是“如何在我的函数之外获得结果”。

在您的函数rename 中将rename 签名更改为public string rename 和return filename。

我删除了 try catch,因为您在此示例中不需要它。

public string rename(string Number, string Type)
{
    string filename = " ";

    if (Number.Contains("V2"))
    {
        filename = Number + Type;
    }
    return filename;
}

还有其他方法可以从函数中获取返回值。 喜欢outref。 或者干脆返回一个包含多个值的结构体。

【讨论】:

  • 感谢您的建议。我这样做了,但是重命名签名中显示了此错误:'Form1.rename(字符串,字符串,字符串,字符串,字符串,字符串,字符串,布尔)':并非所有代码路径都返回值。在我的真实代码中,rename 有更多的输入,并且输入之间有更多的 if 循环和组合。我想我已经添加了返回文件名;到尽头......
  • 这很难说,我建议你注释掉一段代码来检查哪一个是问题。
  • 这是个好建议!我也这么想。但后来我读了stackoverflow.com/questions/30451454/… 并意识到丢失的一个被抓住了。看来我真的应该花更多时间学习 C# 基础知识.....
  • 当你知之甚少时,最难的是找到从哪里开始。如果你想要一个完整的指南,“head first C#”将是一个好的开始。
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
相关资源
最近更新 更多