缓存反射结果(类属性) [英] Cache Reflection Results (Class Properties)

查看:23
本文介绍了缓存反射结果(类属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到不应该重新评估相当静态的数据而是缓存,我想知道是否可以使用反射获取类属性一次,然后缓存它们,以便我可以动态评估对象属性并读取/分配值,但每次这样做时都没有反射开销.这可能吗(示例代码?)?

considering that fairly static data should not be re-evaluated but cached instead, I wondered if it is possible to use Reflection to obtain class properties once, and then cache them so that I could dynamically evaluate object properties and read/assign values, but not have the Reflection overhead every time I do that. Is this possible (Sample code?) ?

为了澄清一点,假设我有这门课:

To clarify a bit, lets say I have this class:

public class Cloud
{
     Boolean IsWhite;
}

而且我现在正在尝试制作一种方法,允许我做这样的事情(伪代码):

and I'm trying to now make a method that allows me to do something like this (pseudocode):

Update(myCloudInstance, new {IsWhite, true});

Update 现在应该首先检查缓存,如果它已经知道 Cloud 的属性 (typeof(myCloudInstance)),然后使用缓存信息为属性IsWhite"分配值true",而不是再次进行反射.

Update should now check with the cache first if it knows already the properties of Cloud (typeof(myCloudInstance)), and then use cached information to assign the property "IsWhite" the value "true" instead of doing Reflection again.

关于如何做到这一点的任何想法?

Any ideas on how to do this?

推荐答案

不清楚确切你在做什么,但缓存肯定可以对反射产生影响.

It's not clear exactly what you're doing, but caching can certainly make a difference with reflection.

特别是,如果您正在调用方法(或属性 getter/setter)并且就调用代码而言可以以类型安全的方式执行此操作,则 如果您转换MethodInfo 转换为强类型委托一次,然后重用该委托.

In particular, if you're invoking methods (or property getters/setters) and can do so in a type-safe way as far as the calling code is concerned, it can make a huge difference if you convert the MethodInfo into a strongly-typed delegate once and then reuse that.

如果您能给我们一个完整的示例来说明您正在尝试做什么,那将有助于我们提出更具体的想法甚至代码.如果您只是要缓存一个可能没有那么多(或任何)效果的 PropertyInfo - 普通的 Type.GetProperty(等)方法可能已经相当快.与性能问题一样,关键是衡量您实际在做什么.进行更改并重新测量等

If you could give us a complete example of what you're trying to do, that would help us to come up with more specific ideas or even code. If you're just going to cache a PropertyInfo that may not have as much (or any) effect - it's possible that the normal Type.GetProperty (etc) methods are already pretty fast. As ever with performance questions, the key is to measure what you're actually doing. Make a change and measure again, etc.

这篇关于缓存反射结果(类属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆