This question already has an answer here:
这个问题已经有了答案:
- How to prevent duplicate values in enum? 3 answers
- 如何在枚举中防止重复值?3答案
- Non-unique enum values 6 answers
- 非唯一枚举值6个答案
I just noticed that you can create something like this in C#:
我刚注意到你可以在c#中创建这样的东西:
enum TestEnum
{
First = 1,
Second = 1,
Third = 2
}
[TestMethod]
public void Test()
{
TestEnum test = TestEnum.First;
var en = (TestEnum) 1;//And en is now set to First
}
We would like the enums value to be unique. Right now, I have written a unit test that checks that each value is only used once in our enum. Is there a better way to force the uniqueness?
我们希望枚举值是唯一的。现在,我编写了一个单元测试,它检查每个值在枚举中只使用一次。是否有更好的方法来加强独特性?
1 个解决方案
#1
4
Well enums are used to give meaning to integers. When you say Second = 1 that doesn't make sense but think of an example like that one:
恩,恩,恩,是用来赋予整数意义的。当你说第二个= 1时,这是没有意义的,但想想一个例子:
enum HumanEnum
{
Man = 1,
Woman = 0,
Lady = 0,
Boy = 1,
Girl = 0
}
Let's say 0 and 1 represents the gender, in this way Man and Boy has the same gender value.
假设0和1代表性别,这样男人和男孩的性别价值是相同的。
#1
4
Well enums are used to give meaning to integers. When you say Second = 1 that doesn't make sense but think of an example like that one:
恩,恩,恩,是用来赋予整数意义的。当你说第二个= 1时,这是没有意义的,但想想一个例子:
enum HumanEnum
{
Man = 1,
Woman = 0,
Lady = 0,
Boy = 1,
Girl = 0
}
Let's say 0 and 1 represents the gender, in this way Man and Boy has the same gender value.
假设0和1代表性别,这样男人和男孩的性别价值是相同的。