2016-09-29 85 views
0

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

我需要將任何枚舉傳遞給此方法。任何幫助表示感謝。

+0

可以請您加入鏈接到重複的答案 – wajira000

回答

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

順便說一句,我想你可以替換as TEnum[]與「硬」轉換爲TEnum[],並跳過空檢查:

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

非常感謝。現在它工作正常。你救了我。 – wajira000

+0

如何將TEnum []與TEnum一起使用? – wajira000