即使密钥存在,TryGetValue返回false [英] TryGetValue returns false even though the key exists
问题描述
我有一个称为UnicodeMap的模型类,用于表示十六进制unicode值及其辅音和Amharic字符的值。
I have a model class called UnicodeMap that I use to represent the hexadecimal unicode value and its consonants and values for Amharic characters.
public sealed class UnicodeMap
{
public string Letter;
public string Consonant;
public string Vowel;
}
我已将映射存储为CSV,在运行时中读取以填充字典。
I have stored the mapping in CSV and read in runtime to populate a dictionary.
以下是读取并填充字典的代码摘录:
Here is the excerpt of the code that reads and populates the dictionary:
private Dictionary<string, UnicodeMap> _unicodeMap;
void ReadMap()
{
var engine = new FileHelperAsyncEngine<UnicodeMap>();
using (engine.BeginReadFile(MapFile))
{
foreach (var record in engine)
{
_unicodeMap.Add(record.Letter, record);
}
}
}
当我尝试获取一个使用TryGetValue从字典中获得的值,它总是返回false:
When I try to get a value from the dictionary using TryGetValue, it always returns false:
public void Translate(string text)
{
var words = text.Split(' ', '.');
foreach (var word in words)
{
var chr = Char.Parse(word);
var unicodeStr = @"\u" + ((int) chr).ToString("X4");
UnicodeMap map;
if (_unicodeMap.TryGetValue(unicodeStr, out map)) //returns false
{
_animator.SetTrigger(map.Consonant);
_animator.SetTrigger(map.Vowel);
};
}
}
例如,当字符串为时ሀ , unicodeStr 变量的值为 \u1200。而且我在字典中有一个值为 \u1200的字符串作为键。但是, TryGetValue 似乎无法在字典中找到键。
For example, when the string is "ሀ", the value of the unicodeStr variable is "\u1200". And I have a string with the value "\u1200" as a key in the dictionary. However, TryGetValue cannot seem to find the key in the dictionary.
如何解决此问题?可能的原因是什么?
How can I solve this issue? What is the possible cause?
编辑::添加了调试器的gif,以查看_ unicodeMap 的值。字典
Added a gif of the debugger looking at the values of _unicodeMap dictionary
推荐答案
在gif中很难看到,但是在字典键中的文本后面似乎有一个空格,因此您实际上是在比较 \u1200和 \u1200。
It's a little hard to see in the gif, but it appears you have a trailing space after the text in the dictionary keys, so you are actually comparing "\u1200" and "\u1200 ".
通过对键进行 .Trim()
来固定字典的填充方式。
Fix the way you populate the dictionary by doing a .Trim()
on the key.
private Dictionary<string, UnicodeMap> _unicodeMap;
void ReadMap()
{
var engine = new FileHelperAsyncEngine<UnicodeMap>();
using (engine.BeginReadFile(MapFile))
{
foreach (var record in engine)
{
_unicodeMap.Add(record.Letter.Trim(), record); //Added .Trim()
}
}
}
或修复 FileHelperAsyncEngine
,不要在 Letter
属性中保留尾随空格。
Or fix FileHelperAsyncEngine
to not leave the trailing space in the Letter
property.
这篇关于即使密钥存在,TryGetValue返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!