【发布时间】:2019-07-12 20:01:11
【问题描述】:
我创建了一个自定义属性类
[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>();
}
}
注意,我使用的对象是现实生活中的一个非常简单的版本,我可以有多层嵌套子级或嵌套列表/数组等..
【问题讨论】:
标签: c# .net reflection