开发者

How to define a variable that can be used everywhere?

How do I define a variable that I can use everywhere in my 开发者_Python百科program in C#.


Try looking at the Settings page in the project properties. You can then use:

Properties.Settings.Default.(Whatever variable you want to access)

Keep in mind that this is more used for program settings, but it can work in a pinch.


Global read-only variable is normally done with a static public property

class Glo
{
    private int _n;
    public int n
    {
        get
        {
            return _n;
        }
    }
}

At least, half the problems that globals normally create would go away. Assignment to _n is done somehow within the Glo class.


If checkBox1_CheckedChanged and button1_Click_1 are both in the same class (IOW they are both on the same control/window), then you can just declare a module (class) level variable:

public class MyClass
{
    private string _myString = null;

    private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
    {
        _myString = "some value";
    }

    private void button1_Click_1(object sender, System.EventArgs e)
    {
        //you can now use _myString in this function
    }
}

While your question talks about using a global variable, according to your follow up comment it isn't actually what you need - you simply need a variable that is visible between functions in the same class.


public class Globals { public static int SomeVar; }

But this is usually a bad idea


Web.Config or App.Config -- as long as you simply really only want to use the value anywhere. e.g.

<appSettings>
    <add key="myValue" value="You can see me anywhere!"/>
</appSettings>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜