Dynamic object property populator (without reflection)

前端 未结 2 801
情深已故
情深已故 2020-12-30 15:11

I want to populate an object\'s properties without using reflection in a manner similar to the DynamicBuilder on CodeProject. The CodeProject example is tailored for populat

相关标签:
2条回答
  • 2020-12-30 16:02

    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();
    

    .... ...

    0 讨论(0)
  • 2020-12-30 16:07

    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.

    0 讨论(0)
提交回复
热议问题