[Unity] Use the Attribute feature for enumerations to map enumeration values to strings

         We often use enumeration values ​​during game development. If we want to get a specific string description during an enumeration, we may achieve it in the following way.

1. Implementation through map mapping

public enum CharacterStatusType
{
    None,
    Silence,
    Stun,
    Weakness,
    Knockdown
}


public static Dictionary<CharacterStatusType, string> statusTypeToString = new Dictionary<CharacterStatusType, string>()
{
    { CharacterStatusType.None, "无异常状态" },
    { CharacterStatusType.Silence, "沉默状态" },
    { CharacterStatusType.Stun, "眩晕" },
    { CharacterStatusType.Weakness, "虚弱" },
    { CharacterStatusType.Knockdown, "击倒" }
};

But in this way, each enumeration value has to be written twice, which is not elegant enough, so I plan to implement it in another way.

2. Implementation using Attribute characteristics.

using System;
using System.ComponentModel;

/// <summary>
/// 枚举特性(Attribute)
/// 
/// 示例:
/// 1.定义:
///public enum MovementDirection
///{
///    [Description("向前方移动")]
///    Forward,
///    [Description("向后方移动")]
///    Backward
///}
///public enum CharacterStatusType
///{
///    [Description("无异常状态")]
///    None,
///    [Description("沉默状态")]
///    Silence,
///    [Description("眩晕")]
///    Stun,
///    [Description("虚弱")]
///    Weakness,
///    [Description("击倒")]
///    Knockdown
///}
/// 2.使用:
/// CharacterStatusType status = CharacterStatusType.Silence;
/// string statusString = status.GetDescription();
/// MovementDirection direction = MovementDirection.Forward;
/// string directionString = direction.GetDescription();
/// 
/// </summary>
public static class EnumExtensions
{
    public static string GetDescription<TEnum>(this TEnum enumValue) where TEnum : Enum
    {
        var type = typeof(TEnum);
        var field = type.GetField(enumValue.ToString());
        if (field != null)
        {
            var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return ((DescriptionAttribute)attributes[0]).Description;
            }
        }

        return enumValue.ToString();
    }
}

This makes it much more convenient to use. You can just add any information you want to associate with the enumeration, and it is also very convenient to call.

Guess you like

Origin blog.csdn.net/qq_42608732/article/details/131688921