我正在尝试创建自定义设置类来存储一些用户范围的设置。几个月前我做了这个,它工作得很好,但我不记得所有的细节,不再能访问源代码了。这是我到目前为止所做的:
CustomSettings.cs
internal sealed partial class CustomSettings : global::System.Configuration.ApplicationSettingsBase
{
private static CustomSettings defaultInstance = ((CustomSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new CustomSettings())));
public static CustomSettings Default
{
get
{
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
public global::System.Collections.Generic.List<global::LearningProject.Types.Product> Products
{
get
{
return ((global::System.Collections.Generic.List<global::LearningProject.Types.Product>)(this["Products"]));
}
set
{
this["Products"] = value;
}
}
}
Product.cs
[Serializable]
public class Product
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Id")]
public int Id { get; set; }
}
以下是 App.config 文件,其中包含示例Product
:
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LearningProject.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
<section name="LearningProject.CustomSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
<userSettings>
<LearningProject.CustomSettings>
<setting name="Products" serializeAs="Xml">
<ArrayOfProduct>
<Product>
<Name>Product1</Name>
<Id>ProductID</Id>
</Product>
</ArrayOfProduct>
</setting>
</LearningProject.CustomSettings>
</userSettings>
</configuration>
现在,当我尝试获取null
的列表时,我得到Products
:
List<Product> products = CustomSettings.Default.Products;
这意味着要么我做错了(xml属性,可能?)或者我错过了一步。另请注意,Settings1.settings
(由VS生成)已经存在,而我的CustomSettings
类只是将方法添加到默认的自动生成的设置文件中。我只是想知道是否有人这样做过。任何帮助表示赞赏。
答案 0 :(得分:0)
在app.config中替换
<setting name="Products" serializeAs="Xml">
<ArrayOfProduct>
<Product>
<Name>Product1</Name>
<Id>ProductID</Id>
</Product>
</ArrayOfProduct>
</setting>
要
<setting name="Products" serializeAs="Xml">
<value>
<ArrayOfProduct>
<Product Name="Product1" Id="1" />
</ArrayOfProduct>
</value>
</setting>
我是如何实现这个
的CustomSettings.Default.Products = new List<Product>();
CustomSettings.Default.Products.Add(new Product() { Id = 1, Name = "Product1" });
CustomSettings.Default.Save();
现在本地配置(%appdatalocal%\ project_name .. \ user.config)包含正确的值