Retrieve all fields, including inherited ones, using a custom attribute

I have a custom attribute BacksCachethat I use to mark fields in a class that should be "defaulted" when certain conditions are met.

I am using the following code:

Type type = obj.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);

foreach (FieldInfo field in fields)
{
  foreach (Attribute at in field.GetCustomAttributes(true))
  if (at is BacksCache)
  {
    field.SetValue(obj, Utils.DefaultValue(field.FieldType));
  }
}

This code works fine, provided the class inheritance hierarchy is flat. That is, if type- this is a type that declares all attribute fields, everything is fine. As soon as I have a class Afrom which descends class B( B : A) and Bhas some attribute fields, all things fall apart: only the fields declared Aare detected and are "defaulted".

, , private private volatile, .

, ?

+3
3

BindingFlags.FlattenHierarchy:

, . . , , . .

"" - oops, . , Type.BaseType.

+7

, A B? , . , . , :

    static void Main(string[] args)
    {

        foreach (var prop in typeof(Sub).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
        {
            foreach (var attrib in prop.GetCustomAttributes(typeof(DescriptionAttribute), false))
            {
                Console.WriteLine(prop.Name);
            }
        }

        Console.ReadKey(true);
    }


public class Base
{
    [Description]
    public int IntProp { get; set; }
}

public class Sub : Base
{
    [Description]
    public string StringProp { get; set; }
}

, .

, , Fields. :

    static void Main(string[] args)
    {
        foreach (var prop in typeof(Sub).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
        {
            foreach (var attrib in prop.GetCustomAttributes(typeof(DescriptionAttribute), false))
            {
                Console.WriteLine(prop.Name);
            }
        }

        Console.ReadKey(true);
    }


public class Base
{
    [Description]
    public int X;

    [Description]
    public int IntProp { get; set; }
}

public class Sub : Base
{
    [Description]
    public int Y;

    [Description]
    public string StringProp { get; set; }
}

X Y .

+2

Attribute.GetCustomAttributes . , , :

foreach (Attribute at in Attribute.GetCustomAttributes(field, true))
{
    // Test and set here
}

. Weitao Su GetCustomAttributes.

0

Source: https://habr.com/ru/post/1726863/


All Articles