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 转载请注明出处。
  • 相关阅读:
    第一周。。。
    新人日报1129
    Daily Report-1126
    How to read source code[repost]
    Markdown tutorial [repost]
    蘑菇街面经
    阿里面经
    百度凤巢一二面经
    Mybatis最入门---代码自动生成(generatorConfig.xml配置)
    Maven的生命周期阶段
  • 原文地址:https://www.cnblogs.com/evlon/p/EmitDynamicProperty.html
Copyright © 2011-2022 走看看