如何prevent重复值枚举?prevent

2023-09-02 21:53:27 作者:淡淡的烟味

我不知道有没有办法来prevent的枚举有重复键编译?

例如本枚举下面将编译

 公开枚举EDuplicates
{
    独特,
    重复= 0,
    键= 1,
    编译= 1
}
 

虽然这code

  Console.WriteLine(EDuplicates.Unique);
Console.WriteLine(EDuplicates.Duplicate);
Console.WriteLine(EDuplicates.Keys);
Console.WriteLine(EDuplicates.Compilation);
 

将打印

 复制
重复
钥匙
钥匙
 
熟悉Objective C

解决方案

这是不禁止的语言规范,因此,任何符合标准的C#编译器的应的允许。你总是可以适应单声道编译器来禁止它 - 但坦率地讲它会更简单写一个单元测试扫描程序集的枚举和执行这样的说法

I wonder is there a way to prevent an enum with duplicate keys to compile?

For instance this enum below will compile

public enum EDuplicates
{
    Unique,
    Duplicate = 0,
    Keys = 1,
    Compilation = 1
}

Although this code

Console.WriteLine(EDuplicates.Unique);
Console.WriteLine(EDuplicates.Duplicate);
Console.WriteLine(EDuplicates.Keys);
Console.WriteLine(EDuplicates.Compilation);

Will print

Duplicate
Duplicate
Keys
Keys

解决方案

This isn't prohibited by the language specification, so any conformant C# compiler should allow it. You could always adapt the Mono compiler to forbid it - but frankly it would be simpler to write a unit test to scan your assemblies for enums and enforce it that way.