C# 从另一个类调用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1392017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:59:25  来源:igfitidea点击:

Calling a Variable from another Class

c#classvariablesstatic

提问by

How can I access a variable in one public class from another public class in C#?

如何从 C# 中的另一个公共类访问一个公共类中的变量?

I have:

我有:

public class Variables
{
   static string name = "";
}

I need to call it from:

我需要从以下位置调用它:

public class Main
{
}

Thanks in advance for the help.

在此先感谢您的帮助。

I am working in a Console App.

我在控制台应用程序中工作。

采纳答案by Nathan W

That would just be:

那只会是:

 Console.WriteLine(Variables.name);

and it needs to be public also:

它也需要公开:

public class Variables
{
   public static string name = "";
}

回答by ChaosPandion

You need to specify an access modifier for your variable. In this case you want it public.

您需要为变量指定访问修饰符。在这种情况下,您希望它公开。

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

在此之后,您可以像这样使用变量。

Variables.name

回答by Francis B.

I would suggest to use a variable instead of a public field:

我建议使用变量而不是公共字段:

public class Variables
{
   private static string name = "";

   public static string Name
   { 
        get { return name; }
        set { name = value; }

   }
}

From another class, you call your variable like this:

在另一个类中,您可以像这样调用变量:

public class Main
{
    public void DoSomething()
    {
         string var = Variables.Name;
    }
}

回答by Sandipan

class Program
{
    Variable va = new Variable();
    static void Main(string[] args)
    {
        va.name = "Stackoverflow";
    }
}