关于c#:将枚举传递给方法

Pass enum to method

本问题已经有最佳答案,请猛点这里访问。

我是C新来的。最近我在一个项目上遇到了问题。我需要使用枚举列表生成下拉列表。我找到了一个好的工作样品。但该示例只使用一个枚举。我的要求是对任何枚举使用此代码。我想不出来。我的代码是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        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
2
3
4
5
6
7
8
9
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[];
  // ...

这使您的方法成为泛型。要调用它,请使用例如:

1
GetSelectListItems<Industry>()

顺便说一下,我想你可以用"硬"的TEnum[]来替换as TEnum[],跳过这个空检查:

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