/// <summary>
 /// Common initialization method. Creates an instantiator delegate when the given type if not public.
 /// </summary>
 private void CommonConstruct()
 {
     if (!typeof(T).IsPublic)
     {
         mNewMtd = SurrogateHelper.CreateDefaultConstructorDelegate(typeof(T));
     }
 }
Beispiel #2
0
        public ConstructorData <DefaultConstructorDelegate> GetDefaultConstructor([NotNull] Type type)
        {
            Debug.Assert(type != null);

            return(_cachedDefaultConstructors.GetOrCreate(type, () =>
            {
                DefaultConstructorDelegate ctor = DelegatesFactory.CreateDefaultConstructor(type, out bool hasConstructor);
                return new ConstructorData <DefaultConstructorDelegate>(ctor, hasConstructor);
            }));
        }
Beispiel #3
0
        public static DefaultConstructorDelegate CreateDefaultConstructorDelegate(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("genericType");
            }


            ConstructorInfo defaultConstructor = type.GetConstructor(Type.EmptyTypes);

            if (defaultConstructor == null)
            {
                return(null);
            }
            // Specify the types of the parameters of the dynamic method. This
            // dynamic method has no parameters.
            Type[] methodArgs = Type.EmptyTypes;

            // Create a dynamic method with the name "", a return type
            // of void, and two parameters whose types are specified by
            // the array methodArgs. Create the method in the module that
            // defines the type.
            DynamicMethod method = new DynamicMethod(String.Empty,
                                                     MethodAttributes.Public | MethodAttributes.Static,
                                                     CallingConventions.Standard,
                                                     typeof(object),
                                                     methodArgs,
                                                     type,
                                                     true);

            // Get an ILGenerator and emit a body for the dynamic method,
            ILGenerator il = method.GetILGenerator();

            EmitDefaultCreatorMethod(type, il);

            DefaultConstructorDelegate deleg =
                (DefaultConstructorDelegate)method.CreateDelegate(typeof(DefaultConstructorDelegate));

            return(deleg);
        }