using System; using System.Collections.Generic; using System.Reflection;
publicstaticclassDataMapper { // 将字典数据映射到对象 publicstatic T MapToObject<T>(Dictionary<string, object> data) where T : new() { T obj = new T(); Type type = typeof(T);
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { var attribute = field.GetCustomAttribute<MapToAttribute>(); if (attribute != null && data.TryGetValue(attribute.Key, outobjectvalue)) { // 类型转换处理 object convertedValue = Convert.ChangeType(value, field.FieldType); field.SetValue(obj, convertedValue); } }
// 处理属性(可选) foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var attribute = prop.GetCustomAttribute<MapToAttribute>(); if (attribute != null && data.TryGetValue(attribute.Key, outobjectvalue)) { prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType)); } }
return obj; } }
使用示例
1 2 3 4 5 6 7 8 9 10 11 12 13
// 模拟从数据库/JSON获取的数据 var data = new Dictionary<string, object> { { "user_name", "Alice" }, { "age", 30 }, { "registration_date", "2023-10-01" } };
// 自动映射数据到对象 User user = DataMapper.MapToObject<User>(data);
Console.WriteLine(user.Name); // 输出: Alice Console.WriteLine(user.RegisterDate); // 输出: 2023/10/01
高级优化
1. 支持嵌套对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassAddress { [MapTo("city")] publicstring City { get; set; } }