如何防止枚举中的重复值?

发布于 2024-08-04 14:02:36 字数 458 浏览 2 评论 0原文

我想知道有没有办法防止带有重复键的枚举进行编译?

例如下面的这个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

濫情▎り 2024-08-11 14:02:36

这是一个简单的单元测试来检查它,应该更快一点:

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

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());
}
过潦 2024-08-11 14:02:36

语言规范并未禁止这样做,因此任何符合要求的 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.

染墨丶若流云 2024-08-11 14:02:36

检查枚举并显示哪些特定枚举值具有重复项的单元测试:

[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));
}

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));
}
嗼ふ静 2024-08-11 14:02:36

另外,如果您想测试项目中的所有枚举:

   [Test]
    public void EnumsDoNotHaveDuplicates()
    {
        IEnumerable<Type> enums = typeof(MyEnum).Assembly
            .GetTypes()
            .Where(t => t.IsEnum && t.IsPublic);

        foreach (Type t in enums)
        {
            MethodInfo method = typeof(EnumTestFixture).GetMethod(nameof(VerifyEnumHasNoDuplicates));
            MethodInfo generic = method.MakeGenericMethod(t);
            generic.Invoke(this, null);
        }
    }

    public void VerifyEnumHasNoDuplicates<T>()
    {
        T[] values = (T[])Enum.GetValues(typeof(T));
        Assert.IsTrue(values.Count() == values.Distinct().Count(), $"{typeof(T).Name} has duplicates!");
    }

MyEnum 替换为应测试的程序集中的任何 Type

如果您不喜欢反射方法,或者您更喜欢对每个枚举进行测试(无论出于何种原因),您仍然可以使用通用方法:

VerifyEnumHasNoDuplicates()

Just as addition, if you want to test ALL enums inside your project:

   [Test]
    public void EnumsDoNotHaveDuplicates()
    {
        IEnumerable<Type> enums = typeof(MyEnum).Assembly
            .GetTypes()
            .Where(t => t.IsEnum && t.IsPublic);

        foreach (Type t in enums)
        {
            MethodInfo method = typeof(EnumTestFixture).GetMethod(nameof(VerifyEnumHasNoDuplicates));
            MethodInfo generic = method.MakeGenericMethod(t);
            generic.Invoke(this, null);
        }
    }

    public void VerifyEnumHasNoDuplicates<T>()
    {
        T[] values = (T[])Enum.GetValues(typeof(T));
        Assert.IsTrue(values.Count() == values.Distinct().Count(), 
quot;{typeof(T).Name} has duplicates!");
    }

Replace MyEnum with the any Type 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>()

热血少△年 2024-08-11 14:02:36
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)));
}

我为您的单元测试提供了简单的测试方法。

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.

疯了 2024-08-11 14:02:36

另一种解决方案是根据所选列具有唯一值,

var uniqueData = temp.Select(u => new tblschClassSchedule
            {
                TeacherName = u.TeacherName,
                SubjectName = u.SubjectName,

            }).Distinct() ;

这将仅获得 2 列,并且仅获得这些列的唯一数据

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文