C# 获取嵌套的泛型类型对象';在运行时通过反射获取属性和属性值
我创建了一个自定义属性类C# 获取嵌套的泛型类型对象';在运行时通过反射获取属性和属性值,c#,.net,reflection,C#,.net,Reflection,我创建了一个自定义属性类 [AttributeUsage(AttributeTargets.Property)] 公共类MyCustomAttribute:属性 { 公共字符串名称{get;set;} } 我在下面有一个复杂的嵌套对象: 公共类父类 { [MyCustom(Name=“父属性1”)] 公共字符串ParentProperty1{get;set;} [MyCustom(Name=“父属性2”)] 公共字符串ParentProperty2{get;set;} 公共子ChildObj
[AttributeUsage(AttributeTargets.Property)]
公共类MyCustomAttribute:属性
{
公共字符串名称{get;set;}
}
我在下面有一个复杂的嵌套对象:
公共类父类
{
[MyCustom(Name=“父属性1”)]
公共字符串ParentProperty1{get;set;}
[MyCustom(Name=“父属性2”)]
公共字符串ParentProperty2{get;set;}
公共子ChildObject{get;set;}
}
公营儿童
{
[MyCustom(Name=“子属性1”)]
公共字符串ChildProperty1{get;set;}
[MyCustom(Name=“子属性2”)]
公共字符串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 void GetObjectInfo(T对象)
{
//获取属性的对象列表。
var properties=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(属性中的var属性)
{
//获取每个属性的属性对象。
var attribute=property.GetCustomAttribute();
}
}
注意,我使用的对象是现实生活中非常简单的版本,我可以有多层嵌套的子对象或嵌套的列表/数组等。您可以创建一个函数,使用自定义属性递归枚举属性
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();