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

        }
    }

  

相关文章:

  • 2021-12-30
  • 2022-01-18
  • 2022-12-23
  • 2022-01-01
  • 2021-12-15
  • 2021-05-18
  • 2021-05-31
  • 2021-11-07
猜你喜欢
  • 2022-12-23
  • 2021-08-05
  • 2021-10-30
  • 2022-12-23
  • 2022-01-23
  • 2021-04-21
相关资源
相似解决方案