开发者

What is the fastest way to get values of properties from an unknown object?

I am using reflection to get property values from the unknown object. I always know the properties of the unknown object at run-time. So, I just want to get the values of those properties from that object. Reflection works for 开发者_JAVA技巧me but I have performance concerns.

Is there any other way we can achieve this efficiently? Can we use serialization? Any out of the box approach?


Some time ago I implemented a property access mechanism which uses Delegate.CreateDelegate and seemed to be faster than simple reflection. You can find it on GitHub.


If you always know the property and you can modify the "unknown" objects, have each of the unknown objects implement a common interface. This way you can type cast the object to the interface that you define and call the properties directly.

If you cannot modify the objects directly and they are not sealed, you can derive a class from the object and mark it as implementing the interface and you are still to go.

Also, your performance concerns with reflection should not necessarily rule out using it. Run you own timing studies and see if the performance hit is really worth worrying about.

If you do use reflection and are interested in more than one property, you will be better of calling GetProperties once and looping through to find the ones that you need than to call GetProperty multiple times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜