反思:设置大量的对象使用动态方法的性质 [英] Reflection: Setting properties of lots of objects using Dynamic Methods

查看:142
本文介绍了反思:设置大量的对象使用动态方法的性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有成千上万的泛型类型T的对象的,我想将它们转换成对象的数组我得到了。
所以我一定要得到的属性列表T,并且每个属性的值设置为相应的对象的数组

So I have thousands of objects, of generic type T, and I want to cast them to an array of objects I got. So I have to get the properties list T, and for each property set the value to the corresponding object on the array

for (int i = 0; reader.Read(); i++)
{
    T tmp = (T)Activator.CreateInstance(typeof(T));
    foreach (var prop in properties)
    {         
        prop.SetValue(tmp, reader.GetValue(reader.GetOrdinal(prop.Name)), null);
    }
}



阅读器是一个DataReader。我的问题是, prop.SetValue 的可悲的是缓慢的(像消耗的总excecution时间的50%),我已经告诉使用动态方法或表达式树,我尝试使用表达式目录树但是从我的理解我不得不产生一棵树,我要设置的每个值,就不会这么好。
所以动态方法是另一种选择。理想的情况是我需要创建一个方法的 SetProp(对象,propertyName的,值)的,我可以重用一遍又一遍。

reader is a DataReader. The problem I have is that prop.SetValue is sadly slow (consumes like 50% of the total excecution time), I've been told to use Dynamic Methods or Expression Trees, I tried using expression trees but from what I understood I have to generate one tree for each value I want to set, which wouldn't be so good. So Dynamic Methods is the other option. Ideally I'd need to create a method SetProp(object, propertyName, value) which I can reuse over and over again.

推荐答案

FastMember ;无论是用它现况,或窃取所有的代码( DynamicMethod的等)。这一切都是与反思缓存等在建实例:

Look at FastMember; either use it "as is", or steal all the code (DynamicMethod, etc). It does all this, with reflection-cache etc built in. Example usage:

var accessor = TypeAccessor.Create(typeof(T)); 
for (int i = 0; reader.Read(); i++)
{
    T tmp = (T)Activator.CreateInstance(typeof(T));
    foreach (var prop in properties)
    {         
        accessor[tmp, propName] = newValue; // fill in name/value here
    }
}



或者 - 使用像短小精悍点网,那这是否的处理所有的物化(因为这显然是数据访问代码)。

alternatively - use something like dapper-dot-net, that does that and handles all the materialization (since this is obviously data-access code).

这篇关于反思:设置大量的对象使用动态方法的性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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