How to prevent duplicate values in enum?

前端 未结 5 542
挽巷
挽巷 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 12:43
    public bool ValidateAllDistinct(Type enumType)
    {
        return !Enum.GetNames(enumType).All(outerName
            => Enum.GetNames(enumType).Any(innerName
                => innerName == outerName 
                    ? true 
                    : Enum.Parse(enumType, innerName) != Enum.Parse(enumType, outerName)));
    }
    

    I simple test method for your unittest.

    0 讨论(0)
  • 2020-11-30 12:50

    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.

    0 讨论(0)
  • 2020-11-30 12:58

    another solution to have unique values based on selected columns

    var uniqueData = temp.Select(u => new tblschClassSchedule
                {
                    TeacherName = u.TeacherName,
                    SubjectName = u.SubjectName,
    
                }).Distinct() ;
    

    this will get only 2 columns and only unique data for those columns

    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题