[英]Store a range of values in web.config - what data structure to use
在以下情况下使用的最佳数据结构是什么?
我想根据某些商品的价格收取费用百分比。 例如,如果(最简单的情况,在这里可以有更多的条目。)
Price -> Percentage
<$5 -> 20%
$5-$10 -> 15%
$10-$20 -> 13.5%
>$20 -> 12.5%
我希望它具有灵活性,因此我想将其放在web.config中(或者,如果您认为它是一个更好的主意-在sql server中)
如何实施呢?
您可以使用ConfigurationSections(http://msdn.microsoft.com/zh-cn/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 Server的桌子上; 该表将有4列:
如有必要,我将在应用程序端捕获此数据。 您可以使用SqlCacheDependency对象来确保数据库上的任何更新都能迅速反映在应用程序端。 我不会使用Web.config,因为Web.config最适合键-值对,而且在这种情况下我看不到这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.