TokenNumberFactory數值工廠的分析最簡單,主要是判斷下一個字符是否是數字或者小數點。將分析得到的字符串轉換為double類型,然後 賦值給創建的TokenValue對象即可。TokenNumberFactory代碼如下:
/// <summary>
/// 數值工廠
/// </summary>
/// <remarks>Author:Alex Leo</remarks>
class TokenNumberFactory : TokenFactory
{
/// <summary>
/// 詞法分析
/// </summary>
/// <param name="TokenList">記號對象列表</param>
/// <param name="Code">源表達式</param>
/// <param name="Index">分析序號</param>
/// <remarks>Author:Alex Leo</remarks>
public new static void LexicalAnalysis(List<TokenRecord> TokenList, string Code, ref int Index)
{
int intIndexCurrent = Index;//指向後一個字符
bool blnContinue = true;
char chrTemp;
string strTempWord;
while (blnContinue && intIndexCurrent < Code.Length)
{
chrTemp = Code[intIndexCurrent];
if (char.IsDigit(chrTemp) || chrTemp.Equals('.'))
{
intIndexCurrent += 1;
}
else
{
blnContinue = false;
}
}//while
strTempWord = Code.Substring(Index, intIndexCurrent - Index);//取得臨時字符串
TokenRecord Token = ProduceToken(strTempWord, Index);
TokenList.Add(Token);
Index = intIndexCurrent - 1;//指針移到當前指針的前一位,然後賦值給循環指針
}//LexicalAnalysis
/// <summary>
/// 產生記號對象
/// </summary>
/// <param name="TokenWord">分析得到的單詞</param>
/// <param name="Index">當前序號</param>
/// <returns>記號對象</returns>
/// <remarks>Author:Alex Leo</remarks>
public new static TokenRecord ProduceToken(string TokenWord, int Index)
{
TokenRecord Token = new TokenValue(Index + 1, TokenWord.Length);
Token.TokenValueType = typeof(double);
double dblValue;
if (double.TryParse(TokenWord, out dblValue))
{
Token.TokenValue = dblValue;
}
else
{
throw new SyntaxException(Index, TokenWord.Length, "表達式 " + TokenWord + " 無 法轉換成數值。");
}
return Token;
}//ProduceToken
}//class TokenNumberFactory
通過這些“工廠”類就可以完成把表達式分析成記號對象列表,為程序理解表達式做好了基礎工作。在下一篇中會介紹如何將記 號對象分析成樹視圖,進而通過樹視圖逐級求解。