예제 #1
0
        /// <summary>
        /// Create a dynamic type representation of a constructor
        /// </summary>
        public static DynamicCtor CreateDynamicCtor(this ConstructorInfo constructorInfo, bool allowNonPublic = true)
        {
            if (constructorInfo == null)
            {
                throw new ArgumentNullException(nameof(constructorInfo));
            }

            var declaringType = constructorInfo.DeclaringType;
            var ctorDelegate  = FluentIl.CreateConstructor(declaringType, constructorInfo, allowNonPublic);
            var access        = GetAccessModifiers(constructorInfo);
            var visibility    = GetVisibilityModifiers(constructorInfo);

            return(new DynamicCtor(declaringType, constructorInfo, access, visibility, ctorDelegate));
        }
예제 #2
0
        /// <summary>
        /// Create a dynamic type representation of a constructor
        /// </summary>
        public static DynamicCtor CreateDynamicCtor(this Type declaringType, Type[] parameterTypes,
                                                    bool allowNonPublic = true)
        {
            if (declaringType == null)
            {
                throw new ArgumentNullException(nameof(declaringType));
            }

            var binderFlags = BindingFlags.Instance | BindingFlags.Public;

            if (allowNonPublic)
            {
                binderFlags |= BindingFlags.NonPublic;
            }

            var                 constructorInfo = declaringType.GetConstructor(binderFlags, null, parameterTypes, null);
            CtorDelegate        ctorDelegate;
            AccessModifiers     access;
            VisibilityModifiers visibility;

            if (constructorInfo == null)
            {
                if ((parameterTypes.Length != 0) || (declaringType.IsValueType == false))
                {
                    throw new InvalidOperationException("Constructor is not defined");
                }
                ctorDelegate = FluentIl.CreateConstructor(declaringType, null, allowNonPublic);
                access       = GetAccessModifiers(declaringType);
                visibility   = GetVisibilityModifiers(declaringType);
            }
            else
            {
                ctorDelegate = FluentIl.CreateConstructor(declaringType, constructorInfo, allowNonPublic);
                access       = GetAccessModifiers(constructorInfo);
                visibility   = GetVisibilityModifiers(constructorInfo);
            }
            return(new DynamicCtor(declaringType, constructorInfo, access, visibility, ctorDelegate));
        }