简体   繁体   English

c#如何存储在全局变量中

[英]how to store in a global variable c#

How do I store the voterid into a global variable so I can use it on another form?如何将voterid存储到全局变量中,以便我可以在另一种形式上使用它? I will use this voterid in order to check if the voter has already voted.我将使用这个voterid来检查选民是否已经投票。

MessageBox.Show("Welcome!");
OleDbCommand comd1 = new OleDbCommand();
comd1.Connection = connection;
comd1.CommandText = "SELECT VoterID FROM tbl_voter where Uname='" +
                    txt_user.Text + "' and Pword='" + txt_pass.Text + "'";
voterid = Convert.ToString(comd1.ExecuteScalar());
MessageBox.Show(voterid);

connection.Close();
connection.Dispose();

this.Hide();
vote form3 = new vote();
form3.ShowDialog();

If we are talking about a Windows Forms application, and by "global" you mean "common across the process," then you can use astatic variable .如果我们谈论的是 Windows 窗体应用程序,并且“全局”的意思是“整个过程中的通用”,那么您可以使用静态变量

In this example i create a special class just to hold static variables, and declare one field and one property that will be available to your program and will hold one and only one value across the entire process.在这个例子中,我创建了一个特殊的类来保存静态变量,并声明一个字段和一个属性,这些字段和属性可供您的程序使用,并将在整个过程中保存一个且仅一个值。

static class GlobalVariables
{
    static public string SomeVariable { get; set ; }  //As a property
    static public string SomeOtherVariable;           //As a field
}

Note that if your program is multi-threaded, it may be a good idea to put a critical section around static variables, like this:请注意,如果您的程序是多线程的,那么在静态变量周围放置一个临界区可能是个好主意,如下所示:

static class GlobalVariables
{
    static private string LockObject = new Object();
    static private string _someVariable;

    static public string SomeVariable 
    { 
        get
        {
            lock(LockObject) { return _someVariable; }
        }
        set
        {
            lock(LockObject) { _someVariable = value; }
        }
    }
}

Application state belongs in the application state object.应用状态属于应用状态对象。 WinForms apps don't have one of these but you could create an AppState class and put an instance in a static property on the Program class. WinForms 应用程序没有其中之一,但您可以创建一个 AppState 类并将实例放在 Program 类的静态属性中。 You can then define whatever global state you like as strongly type properties of AppState and reference them from anywhere in your program as Program.AppState.MyGlobalStronglyTypedValue然后,您可以将您喜欢的任何全局状态定义为 AppState 的强类型属性,并从程序中的任何位置将它们引用为Program.AppState.MyGlobalStronglyTypedValue

You can then put the (de)serialisation logic in the AppState class if you need to persist app state.如果您需要保留应用程序状态,则可以将(反)序列化逻辑放在 AppState 类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM