简体   繁体   English

如何检查 C# 的三个枚举之一中是否存在值?

[英]How to check if a value is present in one of the three enums in C#?

I want to select the category of the string value checking in three enums.我想 select 三个枚举中字符串值检查的类别。

CategoryEnum.cs类别枚举.cs

Category1 = 1,
Category2,
Category3

Category1.cs Category1.cs

Value1 = 1,
Value2 = 2

Category2.cs Category2.cs

Value3 = 1,
Value4 = 2

Category3.cs Category3.cs

Value5 = 1,
Value6 = 2

I have a string testValue and I want to check if it is present in Category1, Category2, or Category3 Enums and then return the string CategoryType in which the value is present.我有一个字符串 testValue,我想检查它是否存在于 Category1、Category2 或 Category3 枚举中,然后返回值所在的字符串 CategoryType。 How to do this in C#?如何在 C# 中执行此操作?

If you add the values to a dictionary, you only have to use reflection once.如果将值添加到字典中,则只需使用反射一次。 Define定义

public enum CategoryEnum
{
    Category1 = 1,
    Category2,
    Category3
}

public enum Category1
{
    Value1 = 1,
    Value2 = 2
}

public enum Category2
{
    Value3 = 1,
    Value4 = 2
}

public enum Category3
{
    Value5 = 1,
    Value6 = 2
}

private static Dictionary<string, CategoryEnum> valueDict = new Dictionary<string, CategoryEnum>();

And

private string[] GetEnumValues<T>()
{
    T[] myEnumMembers = (T[])Enum.GetValues(typeof(T));
    return myEnumMembers.Select(e=>e.ToString()).ToArray();
}

Then you can initialize the dictionary like this:然后你可以像这样初始化字典:

foreach (var s in GetEnumValues<Category1>())
{
    valueDict.Add(s, CategoryEnum.Category1);
}
foreach (var s in GetEnumValues<Category2>())
{
    valueDict.Add(s, CategoryEnum.Category2);
}
foreach (var s in GetEnumValues<Category3>())
{
    valueDict.Add(s, CategoryEnum.Category3);
}

And look up a value like this:并查找这样的值:

var cat2Val3 = Category2.Value3;
Console.WriteLine(valueDict[cat2Val3.ToString()]);

Be sure not to overlap value names, though.不过,请确保不要重叠值名称。

I fixed it by adding another value in the categoryenum "Unknown" And then used this code.我通过在 categoryenum“Unknown”中添加另一个值来修复它,然后使用此代码。 Its a little tradeoff but simple.它有点权衡但简单。

private CategoryEnum GetColumnCategory(string value)
        {

            if (Enum.TryParse(value, out Category1 category1))
            {
                return CategoryEnum.Category1;
            }
            else if (Enum.TryParse(dataType, out Category2 category2))
            {
                return CategoryEnum.Category2;
            }
            else if (Enum.TryParse(dataType, out Category3 category3))
            {
                return CategoryEnum.Category3;
            }
            else
            {
                return CategoryEnum.Unknown;
            }

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM