Mar*_*kus 13 c# collections set setting
我试过了
<appSettings >
<add key="List" value="1"/>
<add key="List" value="2"/>
<add key="List" value="3"/>
</appSettings >
Run Code Online (Sandbox Code Playgroud)
和 System.Configuration.ConfigurationManager.AppSettings.GetValues("List");
但我只得到最后一个成员.我怎么能轻易解决这个问题?
Ash*_*ain 24
我已经处理了类似的问题,我用这段代码做了.希望这有助于解决您的问题.
在这种情况下,List(类似于我的URLSection)将在web.config中有一个完整的配置部分,您可以从该部分获取所有值.
<configSections>
<section name="URLSection" type="A.WebConfigSection,A,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/>
</configSections>
<appSettings></appSettings>
<URLSection>
<urlCollection>
<add url="1" value="a"/>
<add url="2" value="b"/>
</urlCollection>
</URLSection>
Run Code Online (Sandbox Code Playgroud)
我为此创建了三个类:ConfigElement,ConfigElementCollection,WebConfigSection.
ConfigElement
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace A
{
public class ConfigElement:System.Configuration.ConfigurationElement
{
[ConfigurationProperty("url",IsRequired=true) ]
public string url
{
get
{
return this["url"] as string;
}
}
[ConfigurationProperty("value", IsRequired = true)]
public string value
{
get
{
return this["value"] as string;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
ConfigElementCollection
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace A
{
public class ConfigElementCollection:ConfigurationElementCollection
{
public ConfigElement this[int index]
{
get
{
return base.BaseGet(index) as ConfigElement;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new ConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ConfigElement)(element)).url;
}
}
}
Run Code Online (Sandbox Code Playgroud)
WebConfigSection
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace A
{
public class WebConfigSection:ConfigurationSection
{
public WebConfigSection()
{
}
[ConfigurationProperty("urlCollection")]
public ConfigElementCollection allValues
{
get
{
return this["urlCollection"] as ConfigElementCollection;
}
}
public static WebConfigSection GetConfigSection()
{
return ConfigurationSettings.GetConfig("URLSection") as WebConfigSection;
}
}
}
Run Code Online (Sandbox Code Playgroud)