/// <summary> /// 抽象表达式类 /// </summary> public abstract class Expression { protected Dictionary<string, int> table = new Dictionary<string, int>(9); public Expression() { table.Add("一", 1); table.Add("二", 2); table.Add("三", 3); table.Add("四", 4); table.Add("五", 5); table.Add("六", 6); table.Add("七", 7); table.Add("八", 8); table.Add("九", 9); } public virtual void Interpret(Context context) { if (context.Statement.Length == 0) { return; }
foreach (string key in table.Keys) { int value = table[key]; if (context.Statement.EndsWith(key + GetPostFix())) { context.Data += value * this.Multiplier(); context.Statement =
context.Statement.Substring
(0, context.Statement.Length - this.GetLength()); } if (context.Statement.EndsWith("零")) { context.Statement =
context.Statement.Substring(0, context.Statement.Length-1); } } } public abstract string GetPostFix(); public abstract int Multiplier(); public virtual int GetLength() { return this.GetPostFix().Length + 1; } }
public class GeExpression : Expression { public override string GetPostFix() { return string.Empty; } public override int Multiplier() { return 1; } public override int GetLength() { return 1; } } public class ShiExpression : Expression { public override string GetPostFix() { return "十"; } public override int Multiplier() { return 10; } } public class BaiExpression : Expression { public override string GetPostFix() { return "百"; } public override int Multiplier() { return 100; } } public class QianExpression : Expression { public override string GetPostFix() { return "千"; } public override int Multiplier() { return 1000; } } public class WanExpression : Expression { public override string GetPostFix() { return "万"; } public override int Multiplier() { return 10000; } }