I am currently using FieldInfo.GetValue
and FieldInfo.SetValue
quite a lot in my programm, which is significantly slowing up my programm.
For PropertyInfo
I use the GetValueGetter
and GetValueSetter
methods so I only use reflection once for a given type. For the FieldInfo
, the methods don't exist.
What is the suggested approach for FieldInfo
?
EDIT: I followed this useful link from CodeCaster's reply. This is a great search direction.
Now the "only" point that I don't get in this answer is how I can cache the getters / setters and re-use them in a generic way, using only the field's name - which is basically what the SetValue
is doing
// generate the cache
Dictionary<string, object> setters = new Dictionary<string, object>();
Type t = this.GetType();
foreach (FieldInfo fld in t.GetFields()) {
MethodInfo method = t.GetMethod("CreateSetter");
MethodInfo genericMethod = method.MakeGenericMethod( new Type[] {this.GetType(), fld.FieldType});
setters.Add(fld.Name, genericMethod.Invoke(null, new[] {fld}));
}
// now how would I use these setters?
setters[fld.Name].Invoke(this, new object[] {newValue}); // => doesn't work without cast....