C#:传递匿名对象时如何读取模型的嵌套属性?
解决方案
当然可以实现,无需指定具体模型类型,只需通过解析嵌套属性路径(用.分隔层级),逐层利用反射遍历属性即可。
原代码问题分析
你的当前方法仅在传入模型的直接属性中查找匹配项,而AddressLine1是Address属性的子属性,并非MyClass的直接成员,自然返回null。
修改后的实现
下面是支持嵌套属性的方法,同时处理了空值、无效路径等边界情况:
protected PropertyInfo GetNestedPropertyInfo(object model, string propertyPath) { if (model == null || string.IsNullOrWhiteSpace(propertyPath)) return null; Type currentType = model.GetType(); string[] propertySegments = propertyPath.Split('.', StringSplitOptions.RemoveEmptyEntries); PropertyInfo targetProperty = null; foreach (string segment in propertySegments) { targetProperty = currentType.GetProperty(segment); if (targetProperty == null) return null; // 更新当前类型为子属性的类型,继续遍历下一层 currentType = targetProperty.PropertyType; } return targetProperty; }
使用示例
针对你的模型,调用方式如下:
var myModel = new MyClass { Address = new AddressClass { AddressLine1 = "测试地址" } }; // 获取直接属性 var nameProp = GetNestedPropertyInfo(myModel, "Name"); // 获取嵌套属性 var addressLine1Prop = GetNestedPropertyInfo(myModel, "Address.AddressLine1");
补充说明
- 方法支持任意层级的嵌套属性,只要传入的路径格式正确(如
"Address.SubAddress.ZipCode")。 - 若你的原始方法意图是返回属性名称字符串,可修改方法返回类型为
string,并在最后返回targetProperty?.Name。 - 匿名对象同样适用,因为匿名对象本质是.NET编译生成的强类型,反射可以正常读取其属性。
内容的提问来源于stack exchange,提问作者Rumpo
相关产品推荐
相关产品推荐

