您可以使用ConfigurationSections(http://msdn.microsoft.com/en-us/library/2tw134k3.aspx)
基本上,它让你序列化,并从你的web.config直接复杂的结构反序列化您定义的C#类。这是一个例子,它可能无法完美工作(甚至不能编译!),但它可以让你了解你可以从ConfigurationSection获得什么。希望能帮助到你。
namespace Project
{
public class PricesConfiguration : System.Configuration.ConfigurationSection
{
public static PricesConfiguration GetConfig()
{
return (PricesConfiguration)System.Configuration.ConfigurationManager.GetSection("pricesConfiguration") ?? new ShiConfiguration();
}
[System.Configuration.ConfigurationProperty("prices")]
public PricesCollection Prices
{
get
{
return (PricesCollection)this["prices"] ??
new PricesCollection();
}
}
}
public class PricesCollection : System.Configuration.ConfigurationElementCollection
{
public PriceElement this[int index]
{
get
{
return base.BaseGet(index) as PriceElement;
}
set
{
if (base.BaseGet(index) != null)
base.BaseRemoveAt(index);
this.BaseAdd(index, value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new PriceElement();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
var price = (PriceElement)element;
return string.Format("{0}-{1}->{2}%",price.Start,price.End,price.Percentage);
}
}
public class PriceElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationProperty("start", IsRequired = false)]
public int? Start
{
get
{
return this["start"] as int?;
}
}
[System.Configuration.ConfigurationProperty("end", IsRequired = false)]
public int? End
{
get
{
return this["end"] as int?;
}
}
[System.Configuration.ConfigurationProperty("percentage", IsRequired = true)]
public string Percentage
{
get
{
return this["percentage"] as string;
}
}
}
}
而且在web.config看起来像:
<configuration>
<configSections>
<section name="pricesConfig" type="Project.PricesConfig, Project"/>
</configSections>
<pricesConfig>
<prices>
<add end="5" percentage="20" />
<add start="5" end="10" percentage="15" />
<add start="10" end="20" percentage="13.5" />
<add start="20" percentage="12.5" />
</prices>
</pricesConfig>
</configuration>
使用它,只需调用
var config = PricesConfiguration.GetConfig();
我结束了使用基于SQL的东西,有2列,lowerrange价格费用。但是,这也是一个很好的解决方案,您可以使用自定义配置对象提到。 – MoXplod 2011-12-25 04:56:22