gpt4 book ai didi

C# 应用程序设置 : Is there a easy way to put a collection into

转载 作者:可可西里 更新时间:2023-11-01 08:02:49 26 4
gpt4 key购买 nike

我试过了

<appSettings >
<add key="List" value="1"/>
<add key="List" value="2"/>
<add key="List" value="3"/>
</appSettings >

System.Configuration.ConfigurationManager.AppSettings.GetValues("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>

我为此创建了三个类:ConfigElement、ConfigElementCollection、WebConfigSection。

配置元素

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;
}
}



}
}

配置元素集合

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;
}
}
}

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;
}
}
}

关于C# 应用程序设置 : Is there a easy way to put a collection into <appSetting>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1755421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com