___枚举帮助类及_如何使用
---帮助类
using system;
using system.collections.generic;
using system.componentmodel;
using system.linq;
using system.web;
namespace webapplication5
{
public class enumhelper
{
/// <summary>
/// 枚举转字典集合
/// </summary>
/// <typeparam name="t">枚举类名称</typeparam>
/// <param name="keydefault">默认key值</param>
/// <param name="valuedefault">默认value值</param>
/// <returns>返回生成的字典集合</returns>
public static dictionary<string, object> enumlistdic<t>(string keydefault, string valuedefault = "")
{
dictionary<string, object> dicenum = new dictionary<string, object>();
type enumtype = typeof(t);
if (!enumtype.isenum)
{
return dicenum;
}
if (!string.isnullorempty(keydefault)) //判断是否添加默认选项
{
dicenum.add(keydefault, valuedefault);
}
string[] fieldstrs = enum.getnames(enumtype); //获取枚举字段数组
foreach (var item in fieldstrs)
{
string description = string.empty;
var field = enumtype.getfield(item);
object[] arr = field.getcustomattributes(typeof(descriptionattribute), true); //获取属性字段数组
if (arr != null && arr.length > 0)
{
description = ((descriptionattribute)arr[0]).description; //属性描述
}
else
{
description = item; //描述不存在取字段名称
}
dicenum.add(description, (int)enum.parse(enumtype, item)); //不用枚举的value值作为字典key值的原因从枚举例子能看出来,其实这边应该判断他的值不存在,默认取字段名称
}
return dicenum;
}
}
}
---控制器
public actionresult enums()
{
dictionary<string, object> droplist = enumhelper.enumlistdic<project_emun>("请选择", "-1");
//c#mvc的方便之处也在这里,list 集合要与下拉框进行绑定可以直接绑定 viewbag.droplist = new selectlist(list,"对象字段1","对象字段2","默认选择");
viewbag.drop = new selectlist(droplist, "value", "key");
return view();
}
--枚举类
public enum project_emun
{
[description("开始")]
开始 = 1,
[description("中断")]
中断 = 2,
[description("结束")]
结束 = 3,
[description("回馈")]
回馈 = 4,
}
上一篇: 幽默俏皮话,像个冷笑话
下一篇: 机智的网友