我想在不使用反射的情况下填充对象的属性,其方式类似于 CodeProject 上的 DynamicBuilder. 。CodeProject 示例专为使用 DataReader 或 DataRecord 填充实体而定制。我在几个 DAL 中使用了这个,效果很好。现在我想修改它以使用字典或其他与数据无关的对象,以便我可以在非 DAL 代码中使用它——我当前使用反射的地方。我对操作码和 IL 几乎一无所知。我只知道它效果很好并且比反射更快。

我尝试修改 CodeProject 示例,但由于我对 IL 的无知,我陷入了两行。

  • 其中之一涉及 dbnulls,我很确定我可能会丢失它,但我不知道它前面和后面的行是否相关,以及其中哪一行也需要删除。
  • 我认为另一个是之前从数据记录中提取值的,现在需要将其从字典中提取出来。我想我可以用我的“property.Value”替换“getValueMethod”,但我不确定。

我也愿意接受其他/更好的剥皮这只猫的方法。

这是到目前为止的代码(注释掉的行是我所坚持的行):

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

public class Populator<T>
{
    private delegate T Load(Dictionary<string, object> properties);
    private Load _handler;
    private Populator() { }
    public T Build(Dictionary<string, object> properties)
    {
        return _handler(properties);
    }
    public static Populator<T> CreateBuilder(Dictionary<string, object> properties)
    {
        //private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new [] { typeof(int) });
        //private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new [] { typeof(int) });
        Populator<T> dynamicBuilder = new Populator<T>();
        DynamicMethod method = new DynamicMethod("Create", typeof(T), new[] { typeof(Dictionary<string, object>) }, typeof(T), true);
        ILGenerator generator = method.GetILGenerator();
        LocalBuilder result = generator.DeclareLocal(typeof(T));
        generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
        generator.Emit(OpCodes.Stloc, result);
        int i = 0;
        foreach (var property in properties)
        {
            PropertyInfo propertyInfo = typeof(T).GetProperty(property.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy | BindingFlags.Default);
            Label endIfLabel = generator.DefineLabel();

            if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
            {
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, i);
                //generator.Emit(OpCodes.Callvirt, isDBNullMethod);
                generator.Emit(OpCodes.Brtrue, endIfLabel);

                generator.Emit(OpCodes.Ldloc, result);
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, i);
                //generator.Emit(OpCodes.Callvirt, getValueMethod);

                generator.Emit(OpCodes.Unbox_Any, property.Value.GetType());
                generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
                generator.MarkLabel(endIfLabel);
            }
            i++;
        }

        generator.Emit(OpCodes.Ldloc, result);
        generator.Emit(OpCodes.Ret);
        dynamicBuilder._handler = (Load)method.CreateDelegate(typeof(Load));
        return dynamicBuilder;
    }
}

编辑:

使用 Marc Gravell 的 PropertyDescriptor 实现(使用 HyperDescriptor),代码被简化了一百倍。我现在有以下测试:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Hyper.ComponentModel;

namespace Test
{
    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main()
        {
            HyperTypeDescriptionProvider.Add(typeof(Person));
            var properties = new Dictionary<string, object> { { "Id", 10 }, { "Name", "Fred Flintstone" } };
            Person person = new Person();
            DynamicUpdate(person, properties);
            Console.WriteLine("Id: {0}; Name: {1}", person.Id, person.Name);
            Console.ReadKey();
        }

        public static void DynamicUpdate<T>(T entity, Dictionary<string, object> properties)
        {
            foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(typeof(T)))
                if (properties.ContainsKey(propertyDescriptor.Name))
                    propertyDescriptor.SetValue(entity, properties[propertyDescriptor.Name]);
        }
    }
}

欢迎对 TypeDescriptor.GetProperties() 和 PropertyDescriptor.SetValue() 的性能考虑因素提出任何评论...

有帮助吗?

解决方案

编辑:所有这些基本上都是 dapper 所做的 - 但 dapper 更加优化。如果我今天写这个答案,它会简单地写成:“使用精巧的”。


如果您对 IL 不太“了解”,还有一些替代方案可以让您获得 IL 的速度和方便的反思。

第一个例子:

超描述符 - 使用自定义 PropertyDescriptor 为您处理 IL 的模型,因此您所拥有的只是类似的代码(加上一行代码以启用 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;
    }
}

第二个例子:

LINQ 表达式 - 相当冗长,但我已经在 usenet 上讨论了这个(以及上面的内容) - 请参阅 这个档案.

其他提示

是的,你可以使用这样的代码:

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

.... ...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top