0

Given an object o, and a member named s, where s is a string, we can use reflection to get the field of o named the contents of s.

As part of this process, presumably we need to look up some table of metadata for the class, to work out both whether the field exists and where it is relative to the base of objects of that class.

But after that, assuming all objects of the same class have the same layout, we shouldn't have to use reflection again. We've now got the offset of the field from the base, we could just do a pointer addition an be in the right spot for any other object of that class.

So is there anyway to "save" the results of a reflection lookup, so they can be reused on different objects of the same type?

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • Possible duplicate of [Caching reflection data](https://stackoverflow.com/questions/6601502/caching-reflection-data) –  Oct 09 '18 at 02:05
  • I don't know if I've ever done this with fields, but I've done it with properties all the time. With a property, you save the getter and/or setter `MethodInfo` objects and invoke them as needed on any object of the same class. I'm pretty sure it works the same way with `FieldInfo` objects. – Flydog57 Oct 09 '18 at 02:37

1 Answers1

1

Something like this?

public class FieldReader<T> {
    private FieldInfo[] _fields;
    public FieldReader() {
        var theType = typeof(T);
        _fields = theType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    }

    public void ShowFieldValuesforObject(T obj) {
        foreach (var field in _fields) {
            var val = field.GetValue(obj);
            Debug.WriteLine($"{field.Name}: {val}");
        }
    }
}

you can use it like this:

public class TestClass {
    private int _age;
    public string _name;

    public TestClass(int age, string name) {
        _name = name;
        _age = age;
    }

    public static void Test() {
        var fieldReader = new FieldReader<TestClass>();
        var obj1 = new TestClass(12, "Angie");
        var obj2 = new TestClass(42, "Bob");
        Debug.WriteLine("Angie:");
        fieldReader.ShowFieldValuesforObject(obj1);
        Debug.WriteLine("Bob:");
        fieldReader.ShowFieldValuesforObject(obj2);
    }
}

If I call TestClass.Test(), I see this:

Angie:
_age: 12
_name: Angie 
Bob:
_age: 42
_name: Bob
Flydog57
  • 6,851
  • 2
  • 17
  • 18