zoukankan      html  css  js  c++  java
  • 使用动态方法生成对象

      创建动态方法,在动态方法中创建对象.这样就可以避免使用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();
                }
  • 相关阅读:
    CF 234 C Weather(粗暴方法)
    给工作赋予的新意义——Leo鉴书78
    获取集合的方法
    VS 统计代码行数
    , ,
    指针的删除动作
    C++ 名称空间
    boost::token_compress_on
    指针与引用
    容器的end()方法
  • 原文地址:https://www.cnblogs.com/student-note/p/12501296.html
Copyright © 2011-2022 走看看