如何将属性一致的dynamic变量转换为特定类对象集合
解决dynamic到
List<PracovnikHmotZodpovednostDropDownListItem>的转换问题 直接强制转换(List<PracovnikHmotZodpovednostDropDownListItem>)dtos行不通,因为dynamic类型在编译时没有明确的类型信息——即便它的结构和目标List完全一致,CLR也无法直接完成这种类型转换。下面给你几种靠谱的解决方案:
方案1:使用序列化/反序列化(最简便)
借助JSON序列化库(比如Newtonsoft.Json或者System.Text.Json),先把dynamic对象序列化成JSON字符串,再反序列化成目标类型。这种方法不需要手动处理每个属性,适合属性较多的场景:
用Newtonsoft.Json实现:
using Newtonsoft.Json; void someMethod(dynamic dtos) { // 先把dynamic序列化为JSON字符串 string json = JsonConvert.SerializeObject(dtos); // 反序列化为目标List类型 List<PracovnikHmotZodpovednostDropDownListItem> dtoList = JsonConvert.DeserializeObject<List<PracovnikHmotZodpovednostDropDownListItem>>(json); }
用System.Text.Json(.NET Core/.NET 5+推荐):
using System.Text.Json; void someMethod(dynamic dtos) { string json = JsonSerializer.Serialize(dtos); List<PracovnikHmotZodpovednostDropDownListItem> dtoList = JsonSerializer.Deserialize<List<PracovnikHmotZodpovednostDropDownListItem>>(json); }
方案2:手动遍历映射(性能更优)
如果追求更高的性能,可以手动遍历dynamic中的每个元素,逐个创建目标类对象并赋值属性。因为你说属性完全一致,赋值会很顺畅:
void someMethod(dynamic dtos) { List<PracovnikHmotZodpovednostDropDownListItem> dtoList = new List<PracovnikHmotZodpovednostDropDownListItem>(); foreach (var item in dtos) { var targetItem = new PracovnikHmotZodpovednostDropDownListItem { ZaznamId = item.ZaznamId, Text = item.Text, Value = item.Value, Disabled = item.Disabled, UpdateStatus = (UpdateStatusEnum)item.UpdateStatus // 如果dynamic里的枚举是数值/字符串,需要显式转换 }; dtoList.Add(targetItem); } }
方案3:使用反射批量映射(适合通用场景)
如果需要处理多个类似的转换场景,可以用反射来自动匹配属性赋值,避免重复写手动映射的代码:
using System.Reflection; void someMethod(dynamic dtos) { List<PracovnikHmotZodpovednostDropDownListItem> dtoList = new List<PracovnikHmotZodpovednostDropDownListItem>(); Type targetType = typeof(PracovnikHmotZodpovednostDropDownListItem); PropertyInfo[] targetProps = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var item in dtos) { object targetItem = Activator.CreateInstance(targetType); foreach (var prop in targetProps) { // 从dynamic item中获取对应属性的值 dynamic propValue = item.GetType().GetProperty(prop.Name)?.GetValue(item); if (propValue != null) { // 处理枚举类型转换 if (prop.PropertyType.IsEnum) { prop.SetValue(targetItem, Enum.Parse(prop.PropertyType, propValue.ToString())); } else { prop.SetValue(targetItem, Convert.ChangeType(propValue, prop.PropertyType)); } } } dtoList.Add((PracovnikHmotZodpovednostDropDownListItem)targetItem); } }
选哪种方案看你的需求:如果只是单次转换,序列化方法最省心;如果是高频转换场景,手动映射或反射映射性能更好。
内容的提问来源于stack exchange,提问作者SonDy
相关产品推荐
相关产品推荐

