使用动态方法生成对象

 

  创建动态方法,在动态方法中创建对象.这样就可以避免使用Activator.CreateInstance 

        /// <summary>
        /// 生成动态方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <returns></returns>
        private static T GeneratorNewObjDelegate<T>(Type type) where T : class
        {
            var method = new DynamicMethod("Method_" + type.FullName, type, Type.EmptyTypes, true);
            var il = method.GetILGenerator();
            var typeConstructor = type.GetConstructor(Type.EmptyTypes);
            if (type != null)
            {
                il.Emit(OpCodes.Newobj, typeConstructor);
                il.Emit(OpCodes.Ret);
                object del = method.CreateDelegate(typeof(T));
                return (T)del;
            }
            return null;
        }

  使用方法为:

  

 var newObj = GeneratorNewObjDelegate<Func<TestDeletegateMethod>>(typeof(TestDeletegateMethod));
            if (newObj != null)
            {
                    newObj();
            }

 

posted @ 2020-03-16 00:09  夏风微凉  阅读(323)  评论(0编辑  收藏  举报