经过多次尝试和研究,想问一下。
class Customer
{
[Foo]
public string Name {get;set;}
public Account Account {get;set;}
}
class Account
{
[Foo]
public string Info {get;set;}
}
我正在尝试获取所有标有 [Foo]
属性的属性。
我做了一些递归但放弃了。这是我尝试过的:
public static IEnumerable<PropertyInfo> GetPropertiesRecursive(this Type type)
{
var visitedProps= new HashSet<string>();
IList<PropertyInfo> propertyInfos = new List<PropertyInfo>();
var currentTypeInfo = type.GetTypeInfo();
while (currentTypeInfo.AsType() != typeof(object))
{
var unvisitedProperties = currentTypeInfo.DeclaredProperties.Where(p => p.CanRead &&
p.GetMethod.IsPublic &&
!p.GetMethod.IsStatic &&
!visitedProps.Contains(p.Name));
foreach (var propertyInfo in unvisitedProperties)
{
visitedProps.Add(propertyInfo.Name);
propertyInfos.Add(propertyInfo);
}
currentTypeInfo = currentTypeInfo.BaseType.GetTypeInfo();
}
return propertyInfos;
}
最佳答案
你可以使用这个
更新了 @pinkfloydx33 评论中的一些要点
public static IEnumerable<(Type Class, PropertyInfo Property)> GetAttributeList<T>(Type type, HashSet<Type> visited = null)
where T : Attribute
{
// keep track of where we have been
visited = visited ?? new HashSet<Type>();
// been here before, then bail
if (!visited.Add(type))
yield break;
foreach (var prop in type.GetProperties())
{
// attribute exists, then yield
if (prop.GetCustomAttributes<T>(true).Any())
yield return (type, prop);
// lets recurse the property type as well
foreach (var result in GetAttributeList<T>(prop.PropertyType, visited))
yield return (result);
}
}
使用
foreach (var result in GetAttributeList<FooAttribute>(typeof(Customer)))
Console.WriteLine($"{result.Class} {result.Property.Name}");
输出
ConsoleApp.Customer Name
ConsoleApp.Account Info
关于c# - 递归获取标有属性的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029972/