How to prevent duplicate values in enum?

前端 未结 5 556
挽巷
挽巷 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条回答
  •  -上瘾入骨i
    2020-11-30 13:04

    Here's a simple unit test that checks it, should be a bit faster:

    [TestMethod]
    public void Test()
    {
      var enums = (myEnum[])Enum.GetValues(typeof(myEnum));
      Assert.IsTrue(enums.Count() == enums.Distinct().Count());
    }
    

提交回复
热议问题