如何prevent重复值枚举? [英] How to prevent duplicate values in enum?

查看:308
本文介绍了如何prevent重复值枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如本枚举下面将编译

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

虽然这code

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

将打印

 复制
重复
钥匙
钥匙
 

解决方案

这是不禁止的语言规范,因此,任何符合标准的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.

这篇关于如何prevent重复值枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆