C#自定义DynamicObject派生类PersonDto如何转换为子类OfficePersonDto
问题原因
- 你用
personDto as OfficePersonDto转换失败是C#类型系统的固有规则:只有运行时实例本身就是OfficePersonDto类型(只是用父类PersonDto变量接收),才能转换成功。你反序列化时直接指定了PersonDto类型,生成的实例根本不是子类类型,as转换自然返回null。 - 反序列化为
PersonDto时,JSON里的Name字段不属于PersonDto的显式属性,所以被存在了DocumentObject的内部字典里,就算你强制转成子类,这部分值也不会自动映射到子类的Name显式属性上。
解决方案
以下3种方案可按需选择:
方案1:序列化重转(代码改动最小)
直接把已有的PersonDto实例序列化成JSON字符串,再反序列化为OfficePersonDto类型,Json.NET会自动把动态字典里的属性和显式属性做匹配映射:
using Newtonsoft.Json; // 已有personDto实例 PersonDto personDto = JsonConvert.DeserializeObject<PersonDto>(json); // 序列化再反序列化为子类 string tempJson = JsonConvert.SerializeObject(personDto); OfficePersonDto officePerson = JsonConvert.DeserializeObject<OfficePersonDto>(tempJson);
优势是不需要修改现有DocumentObject、Dto类定义,可直接实现Id、Name都匹配到显式属性的需求。
方案2:自定义映射方法(性能更优)
在DocumentObject中添加通用转换方法,手动映射显式属性和动态字典属性,避免两次序列化的开销:
- 先修改
DocumentObject中字典的访问修饰符为protected,方便内部访问:
protected Dictionary<string, object> dictionary = new Dictionary<string, object>();
- 给
DocumentObject添加转换方法:
using System.Reflection; public T ConvertTo<T>() where T : DocumentObject, new() { T result = new T(); // 映射父类所有显式属性到子类 var sourceProperties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && p.CanWrite); foreach (var prop in sourceProperties) { var targetProp = typeof(T).GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (targetProp != null && targetProp.CanWrite) { targetProp.SetValue(result, prop.GetValue(this)); } } // 映射动态字典里的属性到子类显式属性或子类动态字典 foreach (var key in dictionary.Keys) { var targetProp = typeof(T).GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (targetProp != null && targetProp.CanWrite) { targetProp.SetValue(result, dictionary[key]); } else { result.dictionary[key] = dictionary[key]; } } return result; }
- 使用时直接调用方法即可:
OfficePersonDto officePerson = personDto.ConvertTo<OfficePersonDto>();
方案3:反序列化阶段直接判断类型(最优解)
如果可以提前判断JSON对应的类型,在反序列化阶段就直接生成对应类型的实例,从根源避免后续转换的问题。比如JSON中存在Name字段就判定为OfficePersonDto:
using Newtonsoft.Json.Linq; JObject jObj = JObject.Parse(json); PersonDto result; if (jObj.ContainsKey("Name") || jObj.ContainsKey("name")) { result = jObj.ToObject<OfficePersonDto>(); } else { result = jObj.ToObject<PersonDto>(); }
该方案没有多余转换开销,也不会出现属性丢失的问题。
内容的提问来源于stack exchange,提问作者chiaDev
相关产品推荐
相关产品推荐

