在 C# 中,我们可以使用属性为枚举添加类似 Java 的字符串描述。具体步骤如下:

  1. 定义枚举类型:
public enum Gender
{
    [Description('男')]
    Male,
    [Description('女')]
    Female,
    [Description('未知')]
    Unknown
}
  1. 定义一个扩展方法,用于获取枚举值对应的字符串描述:
public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        var field = value.GetType().GetField(value.ToString());
        var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
        return attributes != null && attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }
}
  1. 使用枚举时,调用扩展方法获取字符串描述:
var gender = Gender.Male;
var description = gender.GetDescription(); // 返回 '男'

这样,我们就可以为 C# 枚举类型添加类似 Java 的字符串描述了。

C# 枚举添加字符串描述 - 像 Java 一样

原文地址: https://www.cveoy.top/t/topic/nEPw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录