How to prevent duplicate values in enum?

前端 未结 5 565
挽巷
挽巷 2020-11-30 12:36

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

For instance this enum below will compile

public         


        
5条回答
  •  天涯浪人
    2020-11-30 13:00

    Unit test that checks enum and shows which particular enum values has duplicates:

    [Fact]
    public void MyEnumTest()
    {
        var values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
        var duplicateValues = values.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
        Assert.True(duplicateValues.Length == 0, "MyEnum has duplicate values for: " + string.Join(", ", duplicateValues));
    }
    

提交回复
热议问题