Global variable approach in C# Windows Forms application? (is public static class GlobalData the best)

五迷三道 提交于 2019-12-24 06:33:25

问题


I want to have some custom configuration (read in from file) available throughout my C# Windows Forms application.

Is the concept of say:

  1. creating a static class, e.g. "public static class GlobalData"
  2. loading from the "Load" action of the main form event

How does this sound? Is this the best practice way to do it?


回答1:


As others have stated, you can use AppSettings to store simple data. The basics are easy; going beyond them is hard (see App.Config and Custom Configuration Sections). You can also serialize classes to XML or JSON, write custom storage formats, use databases, etc.

Making the configuration available throughout your application is a separate issue. Static classes and Singletons are inherently difficult to test, and introduce coupling throughout your other classes. One option is to create an interface for your configuration data class, create and load the configuration on startup, then pass the interface to any class that needs it (often as a constructor parameter). This is called Dependency Injection.

If you're doing this a lot, there are libraries that will make it easier (after you get past the learning curve). See List of .NET Dependency Injection Containers (IOC).




回答2:


Look up ConfigurationManager.AppSettings.

Sample code at http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx




回答3:


I would hesitate to use a 'GlobalData' static class as it smacks of a generic Utils-type catch-all class which can end up being a dumping ground for all kinds of junk. I would lean more towards using the Windows Forms Settings (whether User or Application settings) to store my configuration information. Then, your configuration data can be retrieved from anywhere in your Winforms project using Properties.Settings.Default.MySetting.

With that said, there are some things that I may save in a static class. For example, I have a static SqlDBConnectionInfo object that contains my server, database, and credentials which may be used for making an Sql Connection object or for doing SMO backup/restore operations. This static object gets instantiated on login and any other class that needs to work with the SQL database in some way can grab the static object.

Edit: One other possibility is if you are deserializing/serializing your configuration data using an instance class, you could create a static property in your Program.cs that would hold the instance of your deserialized configuration object. Then, other classes in your project can refer to your configuration data using: MyProjectName.MyConfigurationObject.




回答4:


I use the default Settings file for simple values like window locations and sizes. It's nice because the settings are compiled into properties for you. You can implement the other settings any way you like.

I do not use application settings files very often in Windows Forms. I used them all the time in ASP.NET. Sometimes, I store information in DataTables in memory and use the DataTable.Load and WriteXml functions to persist the information.

Regarding global access, in Windows Forms, I add a Component class to the project and create a global static instance in Main. I can then reference the instance from all forms and add global data to this component. The data is exposed as properties or via functions.




回答5:


Follow the following steps to accomplish Global Data preservation:

  1. Create a static class for holding data:

static class Globals { static String name; static String email;

    public static String Name
    {
        get { return Globals.name; }
        set { Globals.name = value; }
    }

    public static String Email
    {
        get { return Globals.email; }
        set { Globals.email = value; }
    }

}
  1. If you have login page, populate the static class for instance, otherwise you can populate the static global class anywhere according to your requirement.

    private void btnLogin_Click(object sender, EventArgs e)
    {
    
        if (!validate())
            return;
    
        // for admin
        if (txtUserName.Text == "a" && txtPassword.Text == "a")
        {
            this.Hide();
            Globals.Email = txtUserName.Text;
            Globals.IsAdmin = true;
            Globals.Password = txtPassword.Text;
    
            // show other form
            FrmMain frmmain = new FrmMain();
            frmmain.ShowDialog();
    
            // close application
            //this.Close();
    
        }
    
    }
    


来源:https://stackoverflow.com/questions/1515173/global-variable-approach-in-c-sharp-windows-forms-application-is-public-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!