How to store class object in app config file

2019-09-03 14:20发布

问题:

I have a windows application which has more than one form. From one form another form is shown in the application. In the first form, I am creating an object for a class( which has common info among all the forms). I want to use the same object in all the other forms.

Can I save the class object in App.Config file in the first form and retrieve it in other forms? If so please tell me the way to do and If not, suggest any good way to achieve this.

Thanks in Advance

回答1:

You can create a static class having static properties and refer to it whereever required.



回答2:

I think you should pass the information by using a Method or Property of the second form, not by adding it to the app.config.

Here is the code for Form1

var Form2 = new Form2();
form2.MyObjectToPass = objectToPass // this is the object you want to pass into the new Form
form2.ShowDialog()

Now you can access the property in the newly created form



回答3:

Yes, you can do this by serializing the object and store it in setting in the application's config file.

Imho a better way would be to create a custom configurationsection for your application and then store all the necessary information there.

Msdn on ConfigurationSection

By the way: I'm assuming you actually want to use the information stored in the object in future sessions of the Application as well. If the information is only required for this single instance of the application don't bother with storing it in configuration.

If you DO want to use the same information after closing and restarting the application you'll want to consider the approach I mentioned.



回答4:

You can serialize the object into XML and store it as string.

How to serialize an object to XML by using Visual C# http://support.microsoft.com/kb/815813



回答5:

You should use Program.cs file, in there define a public static method that will get and set the class you want to share at application level.