最快的方式使用反射转换DataReader的名单 [英] Fastest way to use reflection for converting datareader to list

查看:166
本文介绍了最快的方式使用反射转换DataReader的名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用反射来的DataReader转换成泛型集合列表。任何人可以
建议我实现反思我们的最佳方式是什么?我想fastestway?

I am using reflection to convert datareader into the generic collection list. Can anybody suggest me the best way to implement reflection for this? I want the fastestway?

推荐答案

我假设你想要做的是一样的东西:

I assume what you want to do is something like:

List<MyClass> list = LoadFromDataReader<MyClass>(dataReader);

class MyClass
{
    [DataField("FirstName")] public string FirstName { get; set; }
    [DataField("LastName")] public string LastName { get; set; }
}

我按这样做:


  1. 使用 Type.GetProperties PropertyInfo.GetCustomAttribute 来一个字典映射的字段名称放在一起,的PropertyInfo 对象

  2. 电话 PropertyInfo.SetValue 上的每个字段中的每个记录

  1. Using Type.GetProperties and PropertyInfo.GetCustomAttribute to put together a dictionary mapping field names to PropertyInfo objects
  2. Calling PropertyInfo.SetValue on each field in each record

您可以缓存步骤的结果(1),因为字段/属性映射不会应用程序的生命周期中改变。

You can cache the results of step (1), since the field/property mapping isn't going to change during the life of the application.

如果性能是一个问题(即,如果步骤(2)原来是一个瓶颈),那么你必须避免使用反射,并产生code直接设置属性。一对夫妇的替代改进:

If performance is a problem (i.e. if step (2) turns out to be a bottleneck), then you have to avoid using reflection and generate code to set the properties directly. A couple of alternative improvements:


  • 使用系统。codeDOM 来生成一个包含C#类code,根据对各个字段设置属性的 IDataReader的。需要注意的是系统。codeDOM 调用后台的 CSC.EXE 编译器,所以你需要生成此code曾经在启动和重新使用它在每次调用。

  • 使用 System.Reflection.Emit.DynamicMethod 来产生IL code,设置属性。不到运行时开销比系统。codeDOM ,但因为你是原料产生IL,这是更难编写和调试。使用作为最后的选择。

  • Use System.CodeDom to generate a C# class containing code to set the properties according to the respective fields on the IDataReader. Note that System.CodeDom invokes the csc.exe compiler in the background, so you need to generate this code once at startup and re-use it on each call.
  • Use System.Reflection.Emit.DynamicMethod to generate IL code that sets properties. Less runtime overhead than System.CodeDom, but since you're generating raw IL, this is much harder to write and debug. Use as a last option.

这篇关于最快的方式使用反射转换DataReader的名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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