我有这个对象层次结构/图表:
人:
(Name,string)
(Age,int?)
(Guid,Guid?)
(Interests,List<Interest>)
兴趣:
(Name,string)
(IsProfession,bool?)
(RequiredSkills,List<RequiredSkill>)
技能:
(Title,string)
(HoursToAccomplish,int?)
所以,基本上这个用 JSON 表示的实例是:
{
"name": "John",
"age": 38,
"guid": null,
"interests": [
{
"name": "party",
"isProfession": false,
"requiredSkills": []
},
{
"name": "painting",
"isProfession": true,
"requiredSkill": [
{
"title": "optics",
"hoursToAccomplish": 75
}
]
}
]
}
现在在 C# 中,我想将此对象图的一个实例转换为ExpandoObject
然后动态地使用它。我写了这个转换方法:
public ExpandoObject ToExpando(object @object)
{
var properties = @object.GetType().GetProperties();
IDictionary<string, object> expando = new ExpandoObject();
foreach (var property in properties)
{
expando.Add(property.Name, property.GetValue(@object));
}
return (ExpandoObject)expando;
}
它适用于嵌套对象。但这改变了属性的可空性。因此这行代码遇到错误:
// Strongly-typed:
if (person.Guid.HasValue) {
// logic
}
// Expando object:
if (person.Guid.HasValue) { // 'System.Guid' does not contain a definition for 'HasValue'
// logic
}
我应该怎么办?