zoukankan      html  css  js  c++  java
  • 快速动态访问属性

        public static class EmitDynamicProperty
        {
            private static ConcurrentDictionary<string, Delegate> action = new ConcurrentDictionary<string, Delegate>();
            public static TRet DynamicGetProperty<TRet>(this object obj, string propertyName)
            {
                var type = obj.GetType();
                string key = string.Concat(type.FullName, "_", propertyName);
                var gater = action.GetOrAdd(key, k =>
                {
                    var method = type.GetProperty(propertyName).GetGetMethod();
    
                    var dynamicMethod = new DynamicMethod(string.Empty, typeof(TRet), new Type[] { typeof(object) });
    
                    var ilGen = dynamicMethod.GetILGenerator();
                    ilGen.Emit(OpCodes.Ldarg_0);
                    ilGen.Emit(OpCodes.Castclass, type);
                    ilGen.Emit(OpCodes.Callvirt, method);
                    if (method.ReturnType.IsValueType && (!typeof(TRet).IsValueType))
                    {
                        ilGen.Emit(OpCodes.Box, method.ReturnType);
                    }
                    ilGen.Emit(OpCodes.Ret);
    
                    return dynamicMethod.CreateDelegate(typeof(Func<object, TRet>));
    
                });
    
                return ((Func<object, TRet>)gater)(obj);
    
            }
        }
    

      

    QQ:273352165 evlon#126.com 转载请注明出处。
  • 相关阅读:
    记事本02
    助人快乐:笔记本连网
    高性能 架构实例 学习笔记
    食.运动.阅读
    The server name ... address could not be resolved
    Mysql 远程访问
    CSS布局 UI 学习笔记
    MySql 修改root密码
    C#:String类型中的CharAt 方法
    La_Lb_Lc
  • 原文地址:https://www.cnblogs.com/evlon/p/EmitDynamicProperty.html
Copyright © 2011-2022 走看看