c# - 使用枚举初始化字典,名称在当前上下文中不存在

标签 c# dictionary enums initialization

我正在尝试使用字符串作为键和枚举作为值来创建字典。代码:

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/

相关文章:

c++ - 为什么 GNU make 忽略或更改我的 g++ 选项(在命令部分)?

C++ 模板和重载运算符

Python - 迭代和更新嵌套字典和列表

c# - 在 C# 中更改 TextBlock 的背景颜色

C#简单除法问题

c# - 无法更改关系,因为一个或多个外键属性不可为空

python - 按输入的顺序循环 Python 字典

C# 将 XML 值加载到字典中,名称作为索引

python - Python 中基于字符串的枚举

c# - App.Config 停止创建