【问题标题】:Pass enum to method [duplicate]将枚举传递给方法[重复]
【发布时间】:2017-02-07 11:34:19
【问题描述】:

我是 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;
    }

我需要将任何枚举传递给此方法。任何帮助表示感谢。

【问题讨论】:

  • 能否请您添加重复答案的链接

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


【解决方案1】:

也许是这样的:

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>()

顺便说一句,我认为您可以将 as TEnum[] 替换为“硬”转换为 TEnum[] 并跳过该空检查:

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

【讨论】:

  • 非常感谢。现在它工作正常。你救了我。
  • 如何使用 as TEnum[] 和 hard TEnum?
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多