Dynamic object property populator (without reflection)

感情迁移 提交于 2019-11-30 07:48:06

Edit: all of this is basically what dapper does - but dapper is much more optimized. If I was writing this answer today, it would read simply: "use dapper".


If you aren't hugely "up" on IL, there are alternatives that get you the speed of IL and the convenience of reflection.

First example:

HyperDescriptor - uses a custom PropertyDescriptor model that deals with the IL for you, so all you have is code like (plus the one-liner to enable HyperDescriptor):

public static IEnumerable<T> Read<T>(IDataReader reader) where T : class, new() 
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));

    PropertyDescriptor[] propArray = new PropertyDescriptor[reader.FieldCount];
    for (int i = 0; i < propArray.Length; i++)
    {
        propArray[i] = props[reader.GetName(i)];
    }
    while(reader.Read()) {
        T item = new T();
        for (int i = 0; i < propArray.Length; i++)
        {
            object value = reader.IsDBNull(i) ? null : reader[i];
            propArray[i].SetValue(item, value);
        }
        yield return item;
    }
}

Second example:

LINQ expressions - quite lengthy, but I've discussed this (and the above, it turns out) on usenet - see this archive.

Yeah,you can use code like this:

 for (int i = 0; i < dataRecord.FieldCount; i++)
                {

                    PropertyInfo propertyInfo = t.GetProperty(dataRecord.GetName(i));
                    LocalBuilder il_P = generator.DeclareLocal(typeof(PropertyInfo));

                    Label endIfLabel = generator.DefineLabel();

.... ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!