我目前在我的程序中使用FieldInfo.GetValue
和FieldInfo.SetValue
相当多,这大大减慢了我的程序。C#FieldInfo反射选择
对于PropertyInfo
我使用GetValueGetter
和GetValueSetter
方法,所以我只对给定类型使用反射一次。对于FieldInfo
,这些方法不存在。
FieldInfo
的建议方法是什么?
编辑: 我跟着this useful link从CodeCaster's回复。这是一个很好的搜索方向。
现在,我没有得到这个答案的“唯一”一点是我如何缓存getters/setters并以通用的方式重新使用它们,只使用字段的名称 - 基本上是什么SetValue
正在做
// 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....
不使用反射,除非你绝对需要它。 – CodeCaster
FieldInfo是如何获得的?如果您在编译期间知道该字段的名称,我建议为set设置一对lambda表达式并获取该值。 – IllidanS4
@CodeCaster不是重复的,至少不是链接的问题。请注意,链接中的问题与PropertyInfo有关,这是一个关于FieldInfo的问题。这两者之间存在显着差异。 – IllidanS4