将枚举传递给方法

时间:2016-09-29 08:32:00

标签: c# asp.net asp.net-mvc

我是C#的新手。最近我在一个项目上遇到了问题。我需要使用枚举列表生成下拉列表。我找到了一个好工作sample。 但该示例仅使用一个枚举,我的要求是将此代码用于任何枚举。我弄清楚了。我的代码是

        public List<SelectListItem> GetSelectListItems()
        {
         var selectList = new List<SelectListItem>();

         var enumValues = Enum.GetValues(typeof(Industry)) as Industry[];
         if (enumValues == null)
            return null;

        foreach (var enumValue in enumValues)
        {
            // Create a new SelectListItem element and set its 
            // Value and Text to the enum value and description.
            selectList.Add(new SelectListItem
            {
                Value = enumValue.ToString(),
                // GetIndustryName just returns the Display.Name value
                // of the enum - check out the next chapter for the code of this function.
                Text = GetEnumDisplayName(enumValue)
            });
        }

        return selectList;
    }

我需要将任何枚举传递给此方法。任何帮助都是值得赞赏的。

1 个答案:

答案 0 :(得分:2)

也许这个:

public List<SelectListItem> GetSelectListItems<TEnum>() where TEnum : struct
{
  if (!typeof(TEnum).IsEnum)
    throw new ArgumentException("Type parameter must be an enum", nameof(TEnum));

  var selectList = new List<SelectListItem>();

  var enumValues = Enum.GetValues(typeof(TEnum)) as TEnum[];
  // ...

这使您的方法通用。要打电话,请使用例如:

GetSelectListItems<Industry>()

顺便说一下,我认为你可以用&#34; hard&#34;替换as TEnum[]。转为TEnum[]并跳过该空检查:

  var enumValues = (TEnum[])Enum.GetValues(typeof(TEnum));