程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了带有用户友好字符串的Enum ToString大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决带有用户友好字符串的Enum ToString?

开发过程中遇到带有用户友好字符串的Enum ToString的问题如何解决?下面主要结合日常开发的经验,给出你关于带有用户友好字符串的Enum ToString的解决方法建议,希望对你解决带有用户友好字符串的Enum ToString有所启发或帮助;

我使用DescriptionSystem.ComponentModel命名空间中的属性。只需装饰枚举即可:

private enum PublishStatusValue
{
    [Description("Not Completed")]
    NotCompleted,
    Completed,
    Error
};

然后使用以下代码进行检索:

public static String GetDescription<T>(this T enumerationvalue)
    where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
    {
        throw new Argumentexception("EnumerationValue must be of Enum type", "enumerationValue");
    }

    //TrIEs to find a DescriptionAttribute for a potential frIEndly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttributE), falsE);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttributE)attrs[0]).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

解决方法

我的枚举包含以下值:

private enum PublishStatusses{
    NotCompleted,Completed,Error
};

我希望能够以用户友好的方式输出这些值。
我不需要再次从字符串变为值。

大佬总结

以上是大佬教程为你收集整理的带有用户友好字符串的Enum ToString全部内容,希望文章能够帮你解决带有用户友好字符串的Enum ToString所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。