c# - 在运行时通过反射获取嵌套的泛型类型对象的属性和属性值
问题描述
我创建了一个自定义属性类
[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
public string Name{ get; set; }
}
我在下面有一个复杂的嵌套对象:
public class Parent
{
[MyCustom(Name = "Parent property 1")]
public string ParentProperty1 { get; set; }
[MyCustom(Name = "Parent property 2")]
public string ParentProperty2 { get; set; }
public Child ChildObject { get; set; }
}
public class Child
{
[MyCustom(Name = "Child property 1")]
public string ChildPropery1 { get; set; }
[MyCustom(Name = "Child property 2")]
public string ChildProperty2 { get; set; }
}
如果该对象在运行时作为通用对象传入,我想获取每个属性的属性名称列表和属性名称值,如果运行时的输入对象是“父”,我该怎么做?
我知道如何使用下面的代码对平面结构通用对象执行此操作,但我不确定如何检索所有嵌套对象属性和属性,我是否需要使用某种递归函数?
public void GetObjectInfo<T>(T object)
{
//Get the object list of properties.
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
//Get the attribute object of each property.
var attribute = property.GetCustomAttribute<MyCustomAttribute>();
}
}
请注意,我使用的对象是现实生活中非常简单的版本,我可以有多层嵌套子级或嵌套列表/数组等。
解决方案
您可以创建一个使用自定义属性递归枚举属性的函数。
public static IEnumerable<PropertyInfo> EnumeratePropertiesWithMyCustomAttribute(Type type)
{
if (type == null)
{
throw new ArgumentNullException();
}
foreach (PropertyInfo property in type.GetProperties())
{
if (property.HasCustomAttribute<MyCustomAttribute>())
{
yield return property;
}
if (property.PropertyType.IsReferenceType && property.PropertyType != typeof(string)) // only search for child properties if doing so makes sense
{
foreach (PropertyInfo childProperty in EnumeratePropertiesWithMyCustomAttributes(property.PropertyType))
{
yield return childProperty;
}
}
}
}
注意:这个函数接受一个类型。在对象上调用它:
public static IEnumerable<PropertyInfo> EnumeratePropertiesWithMyCustomAttributes(object obj)
{
if (obj == null)
{
throw new ArgumentNullException();
}
return EnumeratePropertiesWithMyCustomAttributes(obj.GetType());
}
要获取完整列表:
Parent parent = new Parent();
PropertyInfo[] propertiesWithMyCustomAttribute = EnumeratePropertiesWithMyCustomAttributes(parent).ToArray();
推荐阅读
- kubernetes - 如何使用 containerd 运行时 ssh 进入种类集群节点?
- javascript - 在悬停时连接美国 D3 JS 县地图中的边界线
- javascript - 如何在 useCallback 和 useEffect React 内部调试?
- c# - 具有多个系列的 C# 图表与 X 轴值不匹配
- python - 当我在json中搞砸时,为什么逗号不分隔?
- swift - 本地记录文件为空 [agora.io] Swift
- mongodb - 如何查询对象数组并仅返回与猫鼬匹配的对象
- python-asyncio - 使用流为 asyncio 编写 pytest 测试用例
- javascript - 出于某种原因,nodemon 卡在“由于更改而重新启动......”
- jupyter-notebook - gsutil rsync CommandException:目标()必须完全匹配 1 个 URL