在方法之间传递变量值...? [英] Passing variable values between methods...?

查看:63
本文介绍了在方法之间传递变量值...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我在 C# 中将值从一个类方法传递到另一个类方法吗?我试过查找它,但我迷失在代码页中,找不到一个简单的例子.请看以下内容:

Can someone help me with passing values from one class method to another in c#. I've tried looking it up, but I get lost in pages of code and I cant find a simple example. Take a look at the following:

//Main Program Program.cs
namespace simplecode
{

    class Program
    {
        static void Main(string[] args)
        {
            Values Values = new Values();
            Values.getName();
        }
    }
}


//Separate class file or object Values.cs 


namespace simplecode
{
    public class Values
    {
        public static void getName()
        {
            Console.Clear();
            Console.Write("Enter name: ");
            string myName = Console.ReadLine();
        }
    }
}

现在,如果我执行这个,主程序会运行 getName 并且我可以存储 myName 变量.如何从主程序或其他单独的类方法中获取 myName 的值?我试图从概念上理解这一点,我需要正确的语法.如果有人可以解释需要什么或提供学习链接 id 不胜感激.

Now, if I execute this the main program runs getName and I can store the myName variable. How do I grab the value of myName from the main program, or another separate class method? Im trying to understand this conceptually and I need the proper syntax. If someone could explain whats needed or provide a study link id appreciate it.

谢谢迈克

推荐答案

你可以让方法返回这个值:

You could have the method return this value:

public static string getName()
{
    Console.Clear();
    Console.Write("Enter name: ");
    return Console.ReadLine();
}

然后在您的主程序中调用该方法并将结果存储在局部变量中:

and then in your main program call the method and store the result in a local variable:

static void Main(string[] args)
{
    string myName = Values.getName();
}

请注意,由于 getName 是静态方法,因此您无需创建 Values 类的实例即可调用它.您可以直接在类型名称上调用它.

Notice that since getName is a static method you do not need to create an instance of the Values class in order to invoke it. You could directly call it on the type name.

另一方面,如果 getName 方法不是静态的:

If on the other hand the getName method wasn't static:

public string getName()
{
    Console.Clear();
    Console.Write("Enter name: ");
    return Console.ReadLine();
}

那么你需要实例:

static void Main(string[] args)
{
    Values values = new Values();
    string myName = values.getName();
}

这篇关于在方法之间传递变量值...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆