c# - 递归获取标有属性的属性

标签 c# reflection

经过多次尝试和研究,想问一下。

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/

相关文章:

c# - .net Youtube api v3 将视频上传到特定帐户

c# - 不允许使用 `?` 检查空值和设置值

c# - 在 DocuSign 模板上预填充选项卡

c# - 使用 nameof 获取当前方法的名称

php - 重构/获取 PHP 函数的源代码

Java Reflections getSubTypeOf 不返回层次结构的所有子类

c# - 如何使用参数调用线程中的方法并返回一些值

c# - 无法从 C#.NET 更新 Access 数据库文件

Java/安卓/ Kotlin : Reflection on private Field and call public methods on it

c# - 如何通过反射找到重载的方法