C# 预测分析表填充代码优化:在非空元素前添加 "->"
C# 预测分析表填充代码优化:在非空元素前添加 '->'
在使用 C# 开发预测分析表时,经常需要在填充预测分析表内容时,使不为空的元素前面加上 '->'。 但是,在使用以下代码时:
private void button6_Click(object sender, EventArgs e)
{
// 获取所有终结符和非终结符
terminals = new List<string>();
nonterminals = new List<string>();
foreach (var item in production)
{
if (!nonterminals.Contains(item.Key))
nonterminals.Add(item.Key);
foreach (var prod in item.Value)
{
foreach (var s in prod)
{
if (IsTerminal(s) && !terminals.Contains(s.ToString()))
terminals.Add(s.ToString());
else if (!IsTerminal(s) && !nonterminals.Contains(s.ToString()))
nonterminals.Add(s.ToString());
}
}
}
terminals.Add('#');
// 初始化预测分析表
table = new Dictionary<string, Dictionary<string, string>>();
foreach (var nonterm in nonterminals)
{
table.Add(nonterm, new Dictionary<string, string>());
foreach (var term in terminals)
{
table[nonterm].Add(term, '');
}
}
// 填充预测分析表
GetSelect(production, firsts, follows);
// 输出预测分析表到 listView3 中
listView3.Columns.Clear();
listView3.Items.Clear();
listView3.View = View.Details;
// 添加第一列
listView3.Columns.Add('', 40);
// 添加终结符列
foreach (var item in terminals)
{
listView3.Columns.Add(item, 40);
}
// 填充表格
foreach (var nonterm in nonterminals)
{
ListViewItem item = new ListViewItem(nonterm);
foreach (var term in terminals)
{
if (!string.IsNullOrEmpty(table[nonterm][term]))
{
item.SubItems.Add('-> ' + table[nonterm][term]);
}
else
{
item.SubItems.Add('');
}
}
listView3.Items.Add(item);
}
}
会导致本来对应位置的元素变成了 '->'。
为了解决这个问题,可以修改代码如下:
if (!string.IsNullOrEmpty(table[nonterm][term]))
{
item.SubItems.Add(table[nonterm][term] + ' ->');
}
else
{
item.SubItems.Add('');
}
修改后的代码将在不为空的元素前面加上 '->'。
修改逻辑解释:
原代码中,item.SubItems.Add('-> ' + table[nonterm][term]); 会将 '-> ' 与 table[nonterm][term] 连接在一起,导致本来对应位置的元素变成了 '->'。
修改后的代码将 table[nonterm][term] 与 ' ->' 连接在一起,实现了在不为空的元素前面加上 '->' 的效果。
通过简单的代码修改,就可以实现预期效果,使预测分析表的填充更符合预期。
原文地址: http://www.cveoy.top/t/topic/oyba 著作权归作者所有。请勿转载和采集!