-1

I'm using Unity and i have a class full of gameObjects, i want to take an instance of that class and compare all the values against one i already have. However in order to do this i need to have the filed value, how do i get this?, Here's my curent code:

void UpdatePage() {
  foreach(FieldInfo field in Pages.GetType().GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) {
    Page = field.GetValue();
  }

}
ADyson
  • 57,178
  • 14
  • 51
  • 63
Isiah
  • 195
  • 2
  • 15
  • _"filed value"_? Is that a typo? Did you mean "field value"? – Wyck Aug 30 '20 at 00:02
  • Does this answer your question? [C# Reflection - Get field values from a simple class](https://stackoverflow.com/questions/7649324/c-sharp-reflection-get-field-values-from-a-simple-class) – devNull Aug 30 '20 at 00:02
  • I would recommend changing your strategy completely. Do not make the fields you are calling static, instead make them instance singletons instead. This will let you hold a `Page[]` in `Pages` and you can foreach over the array instead of being forced to use reflection. – Scott Chamberlain Aug 30 '20 at 00:06
  • why even use reflection for this? I would rather implement `Equals` in the class itself where you have access to all private fields anyway... could you please post a minimal **complete** working code so we can reproduce your situation? – derHugo Aug 30 '20 at 14:44

2 Answers2

2

The GetField() method requires an instance argument:

var val = field.GetValue(Pages);

Here's a self-contained example (also a link to .NET Fiddle):

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var item = new SomeType();
        item.FieldA = "hi";
        item.FieldB = "bye";
        
        foreach(var field in item.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) {
            var val = field.GetValue(item);
            Console.WriteLine("In the 'item' instance, field " + field.Name + " has value " + val);
        }
    }
}

public class SomeType {
    public string FieldA;
    public string FieldB;
}
J. Gómez
  • 96
  • 4
0

You need to pass the target instance to GetValue() (null for static fields):

Page = field.GetValue(field.IsStatic ? null : Pages);
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206