• 使用Emit实现给实体赋值


    代码:

    public static Action<T, object> EmitSetter<T>(string propertyName)
    {
        var type = typeof(T);
        var dynamicMethod = new DynamicMethod("EmitCall", null, new[] { type, typeof(object) }, type.Module);
        var iLGenerator = dynamicMethod.GetILGenerator();
    
        var callMethod = type.GetMethod("set_" + propertyName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
        var parameterInfo = callMethod.GetParameters()[0];
        var local = iLGenerator.DeclareLocal(parameterInfo.ParameterType, true);
    
        iLGenerator.Emit(OpCodes.Ldarg_1);
        if (parameterInfo.ParameterType.IsValueType)
        {
            iLGenerator.Emit(OpCodes.Unbox_Any, parameterInfo.ParameterType); // 如果是值类型,拆箱
        }
        else
        {
            iLGenerator.Emit(OpCodes.Castclass, parameterInfo.ParameterType); // 如果是引用类型,转换
        }
    
        iLGenerator.Emit(OpCodes.Stloc, local);
        iLGenerator.Emit(OpCodes.Ldarg_0);
        iLGenerator.Emit(OpCodes.Ldloc, local);
    
        iLGenerator.EmitCall(OpCodes.Callvirt, callMethod, null);
        iLGenerator.Emit(OpCodes.Ret);
    
        return dynamicMethod.CreateDelegate(typeof(Action<T, object>)) as Action<T, object>;
    }
    View Code

    摘自博客:https://www.cnblogs.com/czly/archive/2018/06/01/9120280.html

  • 相关阅读:
    leetcode887dp
    VMware虚拟机安装Windows7镜像详情
    leetcode双指针21
    N数之和
    leetcode数组151
    leetcodedp877
    leetcode数组189
    leetcodedp64
    解析dxf文件kabeja
    leetcode贪心134
  • 原文地址:https://www.cnblogs.com/s0611163/p/13923496.html
Copyright © 2020-2023  润新知