简体   繁体   中英

Issue with system.reflection, GetFields not returning everything

Im having a bit of an issue with System.Reflection. Please see the attached code:

class Program
{
    public static FieldInfo[] ReflectionMethod(object obj)
    {
        var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
        return obj.GetType().GetFields(flags);
    }
        static void Main()
    {
        var test = new Test() { Id = 0, Age = 12, Height = 24, IsSomething = true, Name = "Greg", Weight = 100 };
        var res = ReflectionMethod(test);
    }
}

    public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsSomething { get; set; }
    public int Weight { get; set; }
    public int Height { get; set; }
    public int CalculationResult => Weight * Height;

    public Test()
    {

    }
}

It seems as though the getfields method is not getting the calculated property CalculationResult. I'm assuming there is another flag I need to use, but I can't figure out which one it is.

Thanks in advance and I'll happily provide more info if necessary.

That is because it is a property and not a field.

=> is a syntactic sugar for a getter which is a property. So it is equivelant to:

public int CalculationResult 
{ 
   get 
   { 
      return Weight * Height; 
   }
}

So you need to use .GetProperties(flags)

Well, analyzing this line of code :

public int CalculationResult => Weight * Height;

Which can also be simplified to (without C# 6.0 syntactic sugar) :

public int CalculationResult {get { return Weight*Height; } }

Compiler doesn't create backing field because it's not auto-property and that's why it is not among the fields retrieved from class by reflection calls.

If you change it to public int CalculationResult { get; } public int CalculationResult { get; } it will create the field and it will show up in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM