use*_*571 2 c# enums dictionary 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}
};
}
Run Code Online (Sandbox Code Playgroud)
所有的大陆名称都显示the name does not exist in the current context,但我不确定为什么。私有枚举和静态Dictionary方法需要保持不变,因此我需要解决此问题。
您应该使用此:
Continent.Africa
Run Code Online (Sandbox Code Playgroud)
而不是使用这个
Africa
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为字典中每个键值对项的值都是类型Continent。如果Africa是一个变量,您已在其中分配了Continent.Africa的值,那么一切都会好起来的。实际上,错误消息通知您Africa在上下文中没有任何变量被调用,更不用说类型问题了。
话虽如此,您应该将代码更改为以下代码:
Dictionary<string, Continent> rivers = new Dictionary<string, Continent>()
{
{"Nile", Continent.Africa},
{"Amazon", Continent.SouthAmerica},
{"Danube", Continent.Europe}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1010 次 |
| 最近记录: |