我正在尝试使用字符串作为键和枚举作为值来创建字典。代码:
private enum Continent { Africa, Antarctica, Asia, Australia, Europe, NorthAmerica, SouthAmerica }
static void DemoDictionary()
{
Console.WriteLine("\n\nDictionary Demo: (rivers)");
Console.WriteLine("=========================\n");
Dictionary<string, Continent> rivers = new Dictionary<string, Continent>()
{
{"Nile", Africa},
{"Amazon", SouthAmerica},
{"Danube", Europe}
};
}
所有大陆名称都显示 该名称在当前上下文中不存在
,我不确定为什么。私有(private)枚举和静态 Dictionary 方法需要保持不变,因此我需要解决这个问题。
最佳答案
你应该使用这个:
Continent.Africa
而不是使用这个
Africa
发生这种情况是因为字典中每个键值对项的值都是Continent
类型。如果 Africa
是一个变量,并且您在其中分配了 Continent.Africa 的值,那么一切都会好起来的。实际上,错误消息告诉您在您的上下文中不存在任何名为 Africa
的变量,更不用说类型问题了。
话虽如此,您应该将代码更改为以下代码:
Dictionary<string, Continent> rivers = new Dictionary<string, Continent>()
{
{"Nile", Continent.Africa},
{"Amazon", Continent.SouthAmerica},
{"Danube", Continent.Europe}
};
关于c# - 使用枚举初始化字典,名称在当前上下文中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027111/