[英]How do I cache FieldInfo.GetValue()?
Okay so I made a class to take an input script and a property name.好的,所以我制作了一个 class 来获取输入脚本和属性名称。 It finds the property and then displays it when Display() is called [ The display method is overridden by a child class ].
它找到属性,然后在调用 Display() 时显示它[显示方法被子 class 覆盖]。 However, there is one problem that I have with it and that is how do I cache what FieldInfo.GetValue() returns?
但是,我遇到了一个问题,那就是如何缓存 FieldInfo.GetValue() 返回的内容? It would be preferable to have a pointer or something to reuse once the variable containing what I need is found since reflection is costly.
一旦找到包含我需要的变量的变量,最好有一个指针或其他东西可以重用,因为反射是昂贵的。
public class PropertyDisplayer : MonoBehaviour
{
public string PropertyName;
public Object TargetObject;
public object _TargetObject;
public FieldInfo Property;
void Start()
{
_TargetObject = TargetObject;
if (!PropertyName.Contains("."))
{
Property = _TargetObject.GetType().GetField(PropertyName);
}
else
{
string[] split = PropertyName.Split('.');
Property = _TargetObject.GetType().GetField(split[0]);
for (int i = 1; i != split.Length; i++)
{
_TargetObject = Property.GetValue(_TargetObject);
Property = Property.FieldType.GetField(split[i]);
}
}
}
public virtual void Display()
{
}
}
Use the dynamitey library, it will cache all reflection calls transparently for you and make them near normal call speed.使用 dynamitey 库,它将为您透明地缓存所有反射调用,并使它们接近正常调用速度。 More info here: https://github.com/ekonbenefits/dynamitey
更多信息在这里: https://github.com/ekonbenefits/dynamitey
You can store the results of the FieldInfo.GetValue() call in a new member field that is of type "object".您可以将 FieldInfo.GetValue() 调用的结果存储在“对象”类型的新成员字段中。 (This IS, effectively, a pointer)
(这实际上是一个指针)
Then, in your Display() override, simply cast this member to the appropriate class, in order to access its members.然后,在您的 Display() 覆盖中,只需将此成员强制转换为适当的 class,以便访问其成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.