Should the Enum values be unique in the global scope?

大城市里の小女人 提交于 2019-12-24 04:03:56

问题


I read in The Fundamentals of Programming course that the enum values should be unique, having the following example:

enum color = { red, orange, yellow };
enum fruit = { apple, orange, kiwi}; // error: orange is redefined
int kiwi = 42; // error: kiwi is redefined

I also found the same idea on this question: Two enums have some elements in common, why does this produce an error?

Enum names are in global scope, they need to be unique.


I write C# apps in MonoDevelop on Ubuntu 14.10 and I tried to reproduce this behavior:

using System;

namespace FP
{
    class MainClass
    {
        enum color { red, orange, yellow };
        enum fruit { apple, orange, kiwi}; // error: orange is redefined
        int kiwi = 42; // error: kiwi is redefined
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello World!");
        }
    }
}

The program above compiled successfully.

Is this a known MonoDevelop behavior or why it was compiled without errors? Should the Enum values be unique in the global scope?


回答1:


What you are talking about is behaviour of the c language.

In c# enums are not globally accessible by name, you always have to access them by typeName.valueName, e.g. color.Orange, fruit.Orange. So there will be no conflict. In fact many in-built enums use the same value names (StringSplitOptions.None, CompareOptions.None).




回答2:


No, it's not a bug, that is how C# is supposed to work. The question that you linked to is about C, not C#.

In C all enum values have to be unique, as you can use the value without specifying which enum it belongs to. That's why the example in that question didn't compile.

In C# the enum values only have to be unique within the same enum. In C# you never use an enum value without specifying which enum it belongs to, so values from different enums doesn't conflict.

The enum values will usually be unique, it goes with trying to make identifiers descriptive. If you happen to use the same name for values in different enums, then there is a reason for that. Either the enums are closely related so that they overlap in meaning, or there is a word with more than one meaning.



来源:https://stackoverflow.com/questions/28136408/should-the-enum-values-be-unique-in-the-global-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!