示例#1
0
        public void CreateConstructor()
        {
            var constructor = DynamicMethodFactory.CreateConstructor(typeof(Contact));

            Assert.NotNull(constructor);

            var contactDelegate = constructor() as Contact;

            Assert.NotNull(contactDelegate);
            Assert.IsType <Contact>(contactDelegate);
        }
        /// <summary>
        /// 返回使用反射优化后动态创建对应类型实例的结果
        /// </summary>
        /// <param name="instanceType">类型</param>
        /// <returns>类型实例</returns>
        public static object FastNew(this Type instanceType)
        {
            if (instanceType == null)
            {
                throw new ArgumentNullException("instanceType");
            }

            CtorDelegate ctor = (CtorDelegate)s_methodDict[instanceType];

            if (ctor == null)
            {
                ConstructorInfo ctorInfo = instanceType.GetConstructor(Type.EmptyTypes);
                ctor = DynamicMethodFactory.CreateConstructor(ctorInfo);
                s_methodDict[instanceType] = ctor;
            }

            return(ctor());
        }
示例#3
0
        /// <summary>
        /// 根据指定的Type,用优化的方式快速创建实例
        /// </summary>
        /// <param name="instanceType"></param>
        /// <returns></returns>
        public static object FastNew(this Type instanceType)
        {
            if (instanceType == null)
            {
                throw new ArgumentNullException("instanceType");
            }

            CtorDelegate ctor = (CtorDelegate)MethodDict[instanceType];

            if (ctor == null)
            {
                ConstructorInfo ctorInfo = instanceType.GetConstructor(Type.EmptyTypes);

                if (ctorInfo == null)
                {
                    throw new NotSupportedException(string.Format("类型\"{0}\"没有无参的构造方法。", instanceType.ToString()));
                }

                ctor = DynamicMethodFactory.CreateConstructor(ctorInfo);
                MethodDict[instanceType] = ctor;
            }

            return(ctor());
        }