Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从StringValue属性的值解析枚举_C#_.net_.net Core - Fatal编程技术网

C# 如何从StringValue属性的值解析枚举

C# 如何从StringValue属性的值解析枚举,c#,.net,.net-core,C#,.net,.net Core,无法从枚举对象的StringValue属性解析为枚举对象 枚举: 解析尝试1 string inputHtmlColor = "#F3212A"; // input StatusColor outColor; // output Enum.TryParse(inputHtmlColor , true, out outColor); 解析尝试2: string inputHtmlColor = "#F3212A"; //input StatusColor outColor = Enum.Pars

无法从枚举对象的StringValue属性解析为枚举对象

枚举:

解析尝试1

string inputHtmlColor = "#F3212A"; // input
StatusColor outColor; // output
Enum.TryParse(inputHtmlColor , true, out outColor);
解析尝试2:

string inputHtmlColor = "#F3212A"; //input
StatusColor outColor = Enum.Parse(typeof(StatusColor), inputHtmlColor, true);

两个代码都不起作用,代码总是选择StatusColor。第一个代码没有。如何获得正确的StatusColor枚举对象?

我已经为此创建了一个方法,如下所示

StringEnum.GetStringValue(Pass Your enum here)
调用这个在公共类中创建的函数

public static string GetStringValue(Enum value)
        {
            string output = null;
            try
            {
                Type type = value.GetType();

                if (_stringValues.ContainsKey(value))
                    output = (_stringValues[value] as StringValueAttribute).Value;
                else
                {
                    ////Look for our 'StringValueAttribute' in the field's custom attributes
                    FieldInfo fi = type.GetField(value.ToString());
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                    {
                        _stringValues.Add(value, attrs[0]);
                        output = attrs[0].Value;
                    }

                }
            }
            catch (Exception)
            {

            }

            return output;

        }

我已经为此创建了一个方法,如下所示

StringEnum.GetStringValue(Pass Your enum here)
调用这个在公共类中创建的函数

public static string GetStringValue(Enum value)
        {
            string output = null;
            try
            {
                Type type = value.GetType();

                if (_stringValues.ContainsKey(value))
                    output = (_stringValues[value] as StringValueAttribute).Value;
                else
                {
                    ////Look for our 'StringValueAttribute' in the field's custom attributes
                    FieldInfo fi = type.GetField(value.ToString());
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                    {
                        _stringValues.Add(value, attrs[0]);
                        output = attrs[0].Value;
                    }

                }
            }
            catch (Exception)
            {

            }

            return output;

        }

我将创建一个反向查找字典,该字典接受枚举值并返回匹配的枚举值:

public static IDictionary<TKey, TEnum> GetReverseEnumLookup<TEnum, TKey, TAttribute>(Func<TAttribute, TKey> selector, IEqualityComparer<TKey> comparer = null)
    where TEnum: struct, IConvertible // pre-C#7.3
    // where TEnum : System.Enum // C#7.3+
    where TAttribute: System.Attribute
{
    // use the default comparer for the dictionary if none is specified
    comparer = comparer ?? EqualityComparer<TKey>.Default;

    // construct a lookup dictionary with the supplied comparer
    Dictionary<TKey, TEnum> values = new Dictionary<TKey, TEnum>(comparer);

    // get all of the enum values
    Type enumType = typeof(TEnum);
    var enumValues = typeof(TEnum).GetEnumValues().OfType<TEnum>();

    // for each enum value, get the corresponding field member from the enum
    foreach (var val in enumValues)
    {
        var member = enumType.GetMember(val.ToString()).First();

        // if there is an attribute, save the selected value and corresponding enum value in the dictionary
        var attr = member.GetCustomAttribute<TAttribute>();
        if (attr != null) 
        {
            values[selector(attr)] = val;
        }
    }
    return values;
}

我将创建一个反向查找字典,该字典接受枚举值并返回匹配的枚举值:

public static IDictionary<TKey, TEnum> GetReverseEnumLookup<TEnum, TKey, TAttribute>(Func<TAttribute, TKey> selector, IEqualityComparer<TKey> comparer = null)
    where TEnum: struct, IConvertible // pre-C#7.3
    // where TEnum : System.Enum // C#7.3+
    where TAttribute: System.Attribute
{
    // use the default comparer for the dictionary if none is specified
    comparer = comparer ?? EqualityComparer<TKey>.Default;

    // construct a lookup dictionary with the supplied comparer
    Dictionary<TKey, TEnum> values = new Dictionary<TKey, TEnum>(comparer);

    // get all of the enum values
    Type enumType = typeof(TEnum);
    var enumValues = typeof(TEnum).GetEnumValues().OfType<TEnum>();

    // for each enum value, get the corresponding field member from the enum
    foreach (var val in enumValues)
    {
        var member = enumType.GetMember(val.ToString()).First();

        // if there is an attribute, save the selected value and corresponding enum value in the dictionary
        var attr = member.GetCustomAttribute<TAttribute>();
        if (attr != null) 
        {
            values[selector(attr)] = val;
        }
    }
    return values;
}
您的电话号码:

string inputHtmlColor = "#F3212A";
StatusColor outColor = inputHtmlColor.GetEnumFromString<StatusColor>();
如果StringValueAttribute的定义不同,请随时更新您的问题以包含该类型定义,必要时我将更新我的答案。

您的呼叫代码:

string inputHtmlColor = "#F3212A";
StatusColor outColor = inputHtmlColor.GetEnumFromString<StatusColor>();
如果StringValueAttribute的定义不同,请随时更新您的问题以包含该类型定义,必要时我将更新我的答案。

这应该可以做到:

public StatusColor GetColor(string color)
{
    return
        Enum.GetValues(typeof(StatusColor))
            .Cast<StatusColor>()
            .First(x => ((StringValueAttribute)typeof(StatusColor)
                        .GetField(x.ToString())
                        .GetCustomAttribute(typeof(StringValueAttribute))).Value == color);
}
这应该做到:

public StatusColor GetColor(string color)
{
    return
        Enum.GetValues(typeof(StatusColor))
            .Cast<StatusColor>()
            .First(x => ((StringValueAttribute)typeof(StatusColor)
                        .GetField(x.ToString())
                        .GetCustomAttribute(typeof(StringValueAttribute))).Value == color);
}

这意味着在进行最小更改的情况下:

Util类:

private static IDictionary<string, StatusColor> _statusColorByHtml = Enum.GetValues(typeof(StatusColor)).Cast<StatusColor>().ToDictionary(k => k.GetStringValue(), v => v);
public static StatusColor GetStatusColor(string htmlColor)
{
    _statusColorByHtml.TryGetValue(htmlColor, out StatusColor color);
    return color;
}

这意味着在进行最小更改的情况下:

Util类:

private static IDictionary<string, StatusColor> _statusColorByHtml = Enum.GetValues(typeof(StatusColor)).Cast<StatusColor>().ToDictionary(k => k.GetStringValue(), v => v);
public static StatusColor GetStatusColor(string htmlColor)
{
    _statusColorByHtml.TryGetValue(htmlColor, out StatusColor color);
    return color;
}

如果链接的问题没有回答你的问题,请在评论@john中标记我,我会重新打开你的问题。嗨@john,你建议的答案与我想要的相反。答案是关于从对象到它的属性值,而我已经有了属性值和I,并将其转换为enum对象。@kame[]表示一个。Hi@kame,[]类似于Java中的@annotation,如果你是Java背景的话。我今天就这么做了。搜索“convert to enum from description attribute”(从描述属性转换为枚举),并将代码更改为使用该属性。如果链接的问题没有回答您的问题,请在注释@john中标记我,让我知道,我将重新打开您的问题。您好@john,您建议的答案与我想要的相反。答案是关于从对象到它的属性值,而我已经有了属性值和I,并将其转换为enum对象。@kame[]表示一个。Hi@kame,[]类似于Java中的@annotation,如果你是Java背景的话。我今天就这么做了。搜索“convert to enum from description attribute”,并将代码更改为使用该属性。嗨@rvchauhan,这不是我要找的。我已经有了GetStringValue方法来将对象转换为字符串属性值。我想要正好相反的。需要从字符串属性值到枚举对象。谢谢嗨@rvchauhan,这不是我要找的。我已经有了GetStringValue方法来将对象转换为字符串属性值。我想要正好相反的。需要从字符串属性值到枚举对象。谢谢嗨,约翰,这不是一个直截了当的回答,但我真的很喜欢有关系字典的想法,看看里面。可能我会创建自己的,对于不区分大小写的问题,我会将关键大小写转换为我存储的大小写。谢谢@δev我只是觉得你可能需要字典提供的某种程度的性能。我不喜欢我见过的其他方法,因为每次需要转换值时,它们都会使用反射来计算整个枚举。这很管用,但效率不高。嗨,约翰,这不是一个直截了当的答案,但我真的很喜欢有关系字典的想法,看看里面。可能我会创建自己的,对于不区分大小写的问题,我会将关键大小写转换为我存储的大小写。谢谢@δev我只是觉得你可能需要字典提供的某种程度的性能。我不喜欢我见过的其他方法,因为每次需要转换值时,它们都会使用反射来计算整个枚举。它能工作,但效率不高。