2sxc:将单个内容项转换为字典的实现方法
将实体转换为字段-值字典的通用实现
通用扩展方法(支持任意实体)
通过反射实现通用扩展方法,可自动遍历实体的所有公共属性/字段,生成键为字段名、值为对应内容的字典,完美适配多字段场景:
public static Dictionary<string, object> ToEntityDictionary<T>(this T entity) { var resultDict = new Dictionary<string, object>(); // 若你的实体用的是【属性(Property)】,启用这段代码 var properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (var prop in properties) { resultDict[prop.Name] = prop.GetValue(entity); } // 若你的实体用的是【字段(Field)】,替换启用这段代码 // var fields = typeof(T).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); // foreach (var field in fields) // { // resultDict[field.Name] = field.GetValue(entity); // } return resultDict; }
使用示例
拿到目标实体后直接调用扩展方法即可:
// 获取John的实体 var thisPerson = AsList(App.Data["Persons"]).Where(n => n.Name == "John").First(); // 转换为字典 var thisPersonDictionary = thisPerson.ToEntityDictionary(); // 直接通过字段名取值 var johnAddress = thisPersonDictionary["Address"]; // 返回"USA" // 遍历所有字段-值对 foreach (var kvp in thisPersonDictionary) { // 按需处理每个字段,比如打印、批量赋值等 Console.WriteLine($"字段名:{kvp.Key},对应值:{kvp.Value}"); }
说明
- 该方法为通用实现,无论实体包含多少字段/属性,都无需修改方法代码,直接复用即可
- 注意区分实体是使用属性(Property)还是字段(Field),对应切换反射API即可
- 反射性能完全满足常规业务场景,若有极高性能需求,可提前缓存实体的属性/字段信息
内容的提问来源于stack exchange,提问作者João Gomes
相关产品推荐
相关产品推荐

