c# - 动态对象属性填充器(无反射)

标签 c# opcode ilgenerator

我想以类似于 DynamicBuilder on CodeProject 的方式在不使用反射的情况下填充对象的属性. CodeProject 示例专为使用 DataReader 或 DataRecord 填充实体而定制。我在几个 DAL 中使用它,效果很好。现在我想修改它以使用字典或其他数据不可知对象,以便我可以在非 DAL 代码中使用它——我目前使用反射的地方。我对 OpCodes 和 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 更优化。如果我今天写这个答案,它会简单地写成:“使用 dapper”。


如果您对 IL 不是很“了解”,则有一些替代方案可以让您获得 IL 的速度和反射的便利性。

第一个例子:

HyperDescriptor - 使用自定义 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 上讨论过这个(事实证明是上面的) - 请参阅 this archive .

关于c# - 动态对象属性填充器(无反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1273589/

相关文章:

c# - 无法连接到远程 SQL Server Express Edition

c# - 如何避免在 RESTful Web API 2 中执行不同的相同操作?

java - Java 类文件上的 ACC_SUPER 访问标志的目的是什么?

c - c 中嵌入的汇编代码为 cmp 提供了不正确的操作数类型错误

c# - 调用不带参数的方法的 IL 代码

c# - C# 中字符串的 Lightswitch NullReferenceException

c# - WPF ComboBox 延迟过滤

php - 为什么 $x=5; $x+++$x++;在 PHP 中等于 11?

c# - ILGenerator 是否有好的包装器?

c# - ILGenerator:如何使用非托管指针? (我得到一个 VerificationException)