3 回答

TA贡献1854条经验 获得超8个赞
导入名称空间:
using System.Configuration;
创建ConfigurationElement公司:
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
和ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
并且您还必须在web.config(app.config)中注册新的配置部分:
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
然后你用
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}

TA贡献1803条经验 获得超6个赞
您应该在CodeProject上查看Jon Rista的有关.NET 2.0配置的三部分系列。
揭示.NET 2.0配置的奥秘
解码.NET 2.0配置的奥秘
揭开.NET 2.0配置之谜
强烈推荐,写得很好,非常有帮助!
它非常清楚地向您展示了如何编写必要的类(来自ConfigurationElement和/或ConfigurationSection),以设计所需的自定义配置部分。

TA贡献1809条经验 获得超8个赞
得注意的是,如果您使用的是MVC应用程序,则列出的部分很好。随着一个控制台应用程序,Web服务,也许还有其他,你需要有“的AssemblyName”‘blablabla.RegisterCompaniesConfig’后
- 3 回答
- 0 关注
- 551 浏览
添加回答
举报