Store array of custom class in settings file
我有一个班:
1 2 3 4 5 6 7 8 9 10 11 | public class CustomClass { public string Columns; public string Filter; public string SourceDB; public string SourceTable; public string DestinationDB; public string DestinationTable; } |
在用户设置中,我需要存储一个CustomClass数组。这是因为我需要用户能够在app.config文件中指定多个customClass。
您必须首先在项目设置文件中创建一个设置,我们将其命名为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="ConsoleApplication1.Properties" GeneratedClassName="Settings"> <Profiles /> <Settings> <Setting Name="CustomClasses" GenerateDefaultValueInCode="false" Type="System.Collections.Generic.List<ConsoleApplication1.CustomClass>" Scope="User"> </Setting> </Settings> </SettingsFile> |
如果打开settings.designer.cs文件,现在应该有:
2您可以在应用程序中保存设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Program { static void Main(string[] args) { Properties.Settings.Default.CustomClasses = new List<CustomClass>() { new CustomClass(){Columns="columns1"}, new CustomClass(){Columns="columns2"}, new CustomClass(){Columns="columns3"}, new CustomClass(){Columns="columns4"} }; Properties.Settings.Default.Save(); } } |
0
1 2 3 4 5 6 7 8 9 10 11 | <configuration> <configSections> <section name="CustomClassSection" type ="A type of class section" /> </configSections> </configuration> <CustomClassSection> <CustomClass Columns="column1" Filter="filter1" SourceDB="sourcedb1" SourceTable="sourcetable1" DestinationDB="destdb1" DestinationTable="desttable1"/> <CustomClass Columns="column2" Filter="filter2" SourceDB="sourcedb2" SourceTable="sourcetable2" DestinationDB="destdb2" DestinationTable="desttable2"/> ... </CustomClassSection> |
You can see how work with sections here: How to create custom config section in app.config?.