C# 字典找不到字符串键

本文关键字:字符串 找不到 字典 | 更新日期: 2023-09-27 17:56:32

我快疯了吗?为什么这会返回异常!?为什么找不到钥匙?它显然在那里!

public class Spanning {
    Dictionary<string, City> graph = new Dictionary<string, City>();
    public static void Main(string[] args) {
        new Spanning().Parse("file.in");
    }
    public void Parse(string f) {
        string[] citySeparator = new string[] {"--"};
        using (StreamReader reader = new StreamReader(f)) {
            string line;
            while((line = reader.ReadLine()) != null) {
                if (!line.Contains("--")) {
                    graph[line] = new City {name = line.Substring(0, line.Length - 1)};
                } else {
                    string[] split = line.Split(citySeparator, StringSplitOptions.None);
                    City city1 = graph[split[0]];
                }
            }
        }
    }
    class City {
        Dictionary<City, int> links = new Dictionary<City, int>();
        public string name;
        public override string ToString() {
            return name;
        }
    }
}

输入文件仅包含两行:

"San Diego" 
"San Diego"--"San Antonio" [1319]

C# 字典找不到字符串键

文件的第一行

"San Diego" 

在最后一个"和换行符之间具有空格字符。

要么修复输入文件,要么使用Trim()来摆脱它:

...
if (!line.Contains("--")) {
    graph[line.Trim()] = new City {name = line.Substring(0, line.Length - 1)};
...