如何防止枚举中的重复值?
我想知道有没有办法防止带有重复键的枚举进行编译?
例如下面的这个enum
将会编译
public enum EDuplicates
{
Unique,
Duplicate = 0,
Keys = 1,
Compilation = 1
}
虽然这个代码
Console.WriteLine(EDuplicates.Unique);
Console.WriteLine(EDuplicates.Duplicate);
Console.WriteLine(EDuplicates.Keys);
Console.WriteLine(EDuplicates.Compilation);
会打印
Duplicate
Duplicate
Keys
Keys
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个简单的单元测试来检查它,应该更快一点:
Here's a simple unit test that checks it, should be a bit faster:
语言规范并未禁止这样做,因此任何符合要求的 C# 编译器都应该允许这样做。您始终可以调整 Mono 编译器来禁止它 - 但坦率地说,编写一个单元测试来扫描程序集的枚举并以这种方式强制执行会更简单。
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.
检查枚举并显示哪些特定枚举值具有重复项的单元测试:
Unit test that checks enum and shows which particular enum values has duplicates:
另外,如果您想测试项目中的所有枚举:
将
MyEnum
替换为应测试的程序集中的任何Type
。如果您不喜欢反射方法,或者您更喜欢对每个枚举进行测试(无论出于何种原因),您仍然可以使用通用方法:
VerifyEnumHasNoDuplicates()
Just as addition, if you want to test ALL enums inside your project:
Replace
MyEnum
with the anyType
in the assembly that should be tested.If you don't like the approach with Reflection or you prefer to have a test per enum (for whatever reason) you can still use the generic method:
VerifyEnumHasNoDuplicates<MyEnum>()
我为您的单元测试提供了简单的测试方法。
I simple test method for your unittest.
另一种解决方案是根据所选列具有唯一值,
这将仅获得 2 列,并且仅获得这些列的唯一数据
another solution to have unique values based on selected columns
this will get only 2 columns and only unique data for those columns