如果您正在学习C#
,您不妨创建一个具有您想要的逻辑的类。在此示例中,我创建了一个ProgressiveTax
对象,您可以调用.Evaluate()
它来计算税款。
您还可以写入或读取XML
字符串(可以写入文件)
例如,首先从PAYE
提供的信息中填充税级并保存到文件PAYE.xml
中。然后忘记税级(超出范围{ }
)。然后读取文件以从文件中填充税表
static class Program
{
static void Main(string[] args)
{
{
// create a tax table and save it to a file
var tax = ProgressiveTax.PAYE();
File.WriteAllText("PAYE.xml", tax.ToXml());
}
{
// read a tax table from a file
var tax = ProgressiveTax.FromXml(File.ReadAllText("PAYE.xml"));
// use the tax table
var x = tax.Evaluate(42250m);
Debug.WriteLine($"Tax={x}");
}
}
}
xml 文件看起来像这样,可以手动编辑,也可以从数据库/webservice 生成。
<?xml version="1.0" encoding="utf-16"?>
<ProgressiveTax xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Credit="2400">
<Brackets>
<Bracket>
<Item1>0</Item1>
<Item2>0.1</Item2>
</Bracket>
<Bracket>
<Item1>24000</Item1>
<Item2>0.15</Item2>
</Bracket>
<Bracket>
<Item1>40667</Item1>
<Item2>0.2</Item2>
</Bracket>
<Bracket>
<Item1>57334</Item1>
<Item2>0.25</Item2>
</Bracket>
</Brackets>
</ProgressiveTax>
以及实际持有税务信息并计算税额的类
public class ProgressiveTax
{
public ProgressiveTax()
{
this.Table = new SortedDictionary<decimal, float>();
}
public ProgressiveTax(SortedDictionary<decimal, float> table)
{
this.Table = table;
}
public static ProgressiveTax PAYE()
{
var tax = new ProgressiveTax();
tax.Credit = 2400m;
tax.Table[0m] = 0.1f;
tax.Table[24000m] = 0.15f;
tax.Table[40667m] = 0.20f;
tax.Table[57334m] = 0.25f;
return tax;
}
public string ToXml()
{
var fs = new StringWriter();
var xs = new XmlSerializer(typeof(ProgressiveTax));
xs.Serialize(fs, this);
fs.Close();
return fs.ToString();
}
public static ProgressiveTax FromXml(string xml)
{
var fs = new StringReader(xml);
var xs = new XmlSerializer(typeof(ProgressiveTax));
var tax = xs.Deserialize(fs) as ProgressiveTax;
fs.Close();
return tax;
}
[XmlAttribute]
public decimal Credit { get; set; }
[XmlIgnore()]
SortedDictionary<decimal, float> Table { get; }
[XmlArrayItem(ElementName = "Bracket")]
public (decimal lower, float rate)[] Brackets
{
get
{
var parts = new (decimal lower, float rate)[Table.Count];
int index = 0;
foreach (var item in Table)
{
parts[index++] = (item.Key, item.Value);
}
return parts;
}
set
{
Table.Clear();
foreach (var (lower, rate) in value)
{
Table[lower] = rate;
}
}
}
public decimal Evaluate(decimal income)
{
decimal result = -Credit;
foreach (var item in Table.Reverse())
{
if (item.Key <= income)
{
Debug.WriteLine($"Assess {item.Value:P2} tax on {income - item.Key}");
result += (decimal)( item.Value * (float) (income - item.Key));
income = item.Key;
}
}
return Math.Max(0m, result);
}
}
示例程序在调试器中产生以下输出。
Assess 20.00% tax on 1583
Assess 15.00% tax on 16667
Assess 10.00% tax on 24000
Tax=2816.65
如果把1583 + 16667 + 24000 = 42250
其中的总收入加起来。由于这是累进税,因此使用上述税率和金额,然后记入 2400。也不是结果必须为 0 或正数。