以下场景使用的最佳数据结构是什么?
我想根据某些商品的价格收取费用百分比。 例如,如果(最简单的场景,这里可以有更多的条目。)
Price -> Percentage
<$5 -> 20%
$5-$10 -> 15%
$10-$20 -> 13.5%
>$20 -> 12.5%
我希望它是灵活的,所以我想把它放在 web.config 中(或者如果你认为它是一个更好的主意 - 在 sql server 中)
如何着手实现?
最佳答案
您可以使用 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();
关于c# - 在 web.config 中存储一系列值 - 使用什么数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627887/