Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - Fastest way to use reflection for converting datareader to list

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume what you want to do is something like:

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

with:

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

I do this by:

  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

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

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:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...