定義一個通用的泛型類,以適應不同需要。
public static class EnumManager<TEnum>
{
//利用反射獲取枚舉中的項
public static DataTable GetDataTable()
{
Type t = typeof(TEnum);//創建類型
FieldInfo[] fieldArray = t.GetFields();//獲取字段信息對象集合
DataTable table = new DataTable();
table.Columns.Add("Name", Type.GetType("System.String"));
table.Columns.Add("Value", Type.GetType("System.Int32"));
//遍歷集合
foreach (FieldInfo field in fieldArray)
{
if (!field.IsSpecialName)
{
DataRow row = table.NewRow();
row[0] = field.Name;
row[1] = Convert.ToInt32(field.GetRawConstantValue());
table.Rows.Add(row);
}
}
return table;
}
}
定義一個枚舉:
public enum OrderStatus
{
未提交 = 1,
已提交 = 2,
已取消 = 3,
受理中 = 4,
已退回 = 5,
已完成 = 6
}
調用結果:
//重構過的通用方法
DataTable table2 = EnumManager<OrderStatus>.GetDataTable();