枚举名称的Enum Extension方法调用?

时间:2017-12-14 11:15:44

标签: c# enums

我有以下代码正常工作。但我需要使用其Enum类型的扩展方法。

public class Dropdown
    {
        public Dropdown() { }
        public Dropdown(int id, string name)
        {
            Id = id;
            Name = name;
        }
        public Dropdown(string name)
        {
            Name = name;
        }
        public int Id { get; set; }
        public string StringId { get; set; }
        public string Name { get; set; }
    }

public enum AccidentTypeEnum
{
    [Display(Name = "Minor")]
    Minor = 0,
    [Display(Name = "Major")]
    Major = 1,
    [Display(Name = "Severe")]
    Severe = 2
}

扩展方法

public static class EnumExtensions
    {
        public static List<Dropdown> ConvertToDropdown(this Enum mEnum)
        {
            var dropDownlist = new List<Dropdown>();

            var enumType = mEnum.GetType();

            var enumValuies = Enum.GetValues(enumType);
            foreach (var singleValue in enumValuies)
            {
                dropDownlist.Add(new Dropdown { Id = (int)singleValue, Name = singleValue.ToString() });

            }

            return dropDownlist;
       }
    }

问题:

如果我使用下面的行调用扩展方法

,上面的代码工作正常
var TestAcident = AccidentTypeEnum.Major;
var resultDropdown = TestAcident.ConvertToDropdown();

但我怎么能像下面的行

那样称呼它
 var resultDropdown = AccidentTypeEnum.ConvertToDropdown(); //<-- i need to use like this. but it not working 

1 个答案:

答案 0 :(得分:0)

您可以做到

List<AccidentTypeEnum> types = Utils<AccidentTypeEnum>.ConvertToDropdown();

这种方式:

/// <summary>Pseudo extension class for enumerations</summary>
/// <typeparam name="TEnum">Enumeration type</typeparam>
public class Utils<TEnum> where TEnum : struct, IConvertible
{
    public static List<Dropdown> ConvertToDropdown()
    {
        var enumType = typeof(TEnum);

        return enumType.IsEnum
            ? enumType.GetEnumValues()
                .OfType<TEnum>()
                .Select(e => new Dropdown
                {
                    Id = Convert.ToInt32(Enum.Parse(enumType, e.ToString()) as Enum),
                    Name = GetDisplay(e)
                })
                .ToList()
            : throw new ArgumentException($"{enumType.Name} is not enum");
    }

    private static string GetDisplay<T>(T value)
    {
        var enumValueText = value.ToString();

        var displayAttribute = value
            .GetType()
            .GetField(enumValueText)
            .GetCustomAttributes(typeof(DisplayAttribute), false)
            .OfType<DisplayAttribute>()
            .FirstOrDefault();

        return displayAttribute == null ? enumValueText : displayAttribute.Description;
    }
}