【发布时间】:2014-12-24 00:50:01
【问题描述】:
我正在创建将莫尔斯电码转换为文本和将文本转换为莫尔斯电码的程序。首先,它适用于字典中的基本字符:abcdefghijklmnoprstuvzy0123456789。比我想升级它以翻译我的语言中的特殊字符,如ščťžýáíéôä?!:;.-_()。问题是当我将它写到我的字典并给出每个字符时键它抛出我异常:System.ArgumentException:已添加具有相同键的项目。
这是我的阅读词典代码
private void ReadDictionary(string filename)
{
string cesta = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
try {
string[] lines = File.ReadAllLines(filename);
if (lines != null) {
}
foreach (string line in lines)
{
string[] znaky = line.Split('=');
string key = znaky[0];
string value = znaky[1];
this.morzeovka.Add(key, value);
this.latinka.Add(value, key);
}
}
catch (IOException) {
MessageBox.Show("Nepodarilo sa nacitat slovnik"+ Environment.NewLine + "Skontrolujete umiestnenie slovníka v: "+cesta,"Chyba",MessageBoxButtons.OK,MessageBoxIcon.Error);
System.Environment.Exit(1);
}
}
}
这是我的字典
a=.-
b=-...
c=-.-.
d=-..
e=.
f=..-.
g=--.
h=....
i=..
j=.---
k=-.-
l=.-..
m=--
n=-.
o=---
p=.--.
q=--.-
r=.-.
s=...
t=-
u=..-
v=...-
w=.--
x=-..-
y=-.--
z=--..
1=.----
2=..---
3=...--
4=....-
5=.....
6=-....
7=--...
8=---..
9=----.
0=-----
.=.-.-.-
,=--..--
?=..--..
!=--..-
;=-.-.-.
:=---...
(=--...
)=-.--.-
""=.-..-.
-=-....-
_=..--.-
@=.--.-.
+=.-.-.
/=-..-.
'=.----.
á=.--.-
ä=.-.-
é=..-..
ö=---.
ü=..--
ň=--.--
这是完全的例外
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
感谢您的帮助,
PS:如果我没有发布足够的代码,请问我应该添加什么
【问题讨论】:
-
那么,迭代中抛出异常的关键是什么?只需在
foreach循环体周围放置一个try { ... } catch (ArgumentException) { System.Diagnostics.Debug.WriteLine(line); throw; }。 -
是的...你为什么不使用调试器来建立坏条目?您的源数据不好,但我们已经确定您在此处发布的数据不是您实际数据的逐字副本。你真的是靠自己。
-
嗯,很抱歉,但我不太理解(我的英语不太好)。如果我运行 debugg 它会向我显示此异常并行 this.latinka.Add(value, key);是黄色的
标签: c#