C#学习之反射机制及应用场景
前言:
假设需要开发一个订单系统,在订单系统中需要表示当前单据的状态。新建,未审核,已审核,。此时,很多开发人员回在数据库中创建单据状态表,命名为StoreStatus (单据状态),如下图所示

在订单系统的其他表中,比如订单表(StoreInfo) 中,通过外键来引用这个表,来获取当前单据状态。如下图所示

然而,经常使用的情况是根据单据状态对单据进行筛选,此时通常的做法是使用一个下拉框(dropdownList) 控件,通过ADO.Net 获取StoreStatus 表的数据,DropDownList 的Text设为Status字段,value设为Id 字段。然后根据选中Id,到数据库进行联合查询,可能查询就像这样:SELECT i.CorpId,i.BizCorpId,s.status FROM dbo.StoreInfo i INNER JOIN dbo.StoreStatus s ON i.StatusId=s.id
采用上面的存在2个问题
1:如果还有别的状态的时候,那么还需要在数据库创建一些小表,从而导致数据库中表的数目过多。
2:使用DropDownList 等控件获取表内容时候,经常需要连接到数据库进行查询,影响了性能。
基于以上问题,反射就应用而生了。解决思路如下, 以上StoreStatus 表 改成枚举,然后后台通过反射枚举值获取当前字段名称和特性,绑定到DropDownList列表,当对当前单据查询的时候,根据当前选择的枚举值转化成int到数据库进行查询。代码如下:
1:将StoreStatus 表值 改成枚举
public enum StoreStatus { [Description("新建")] New, [Description("未审核")] UnAudit, [Description("已审核")] Audited }
2: 通过反射动态的获取枚举字段名称和特性
public static Dictionary<string, string> GetEnumAttribute() { Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var item in typeof(StoreStatus).GetFields()) { if (item.CustomAttributes == null || item.CustomAttributes.Count() <= 0) continue; dic.Add(item.Name, (item.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute).Description); } return dic; }
3:前端进行绑定
<select id=""> @{ foreach (var info in ViewData["dic"] as Dictionary<string, string>) { <option value="@info.Key">@info.Value</option> } } </select>
4:根据选中的值再到单据信息表进行查询。

浙公网安备 33010602011771号