[英]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.