GetConstructors() public method

public GetConstructors ( ) : ConstructorInfo[]
return ConstructorInfo[]
        public static RuleRewriter Create(Type type, ISettings settings, Func<SemanticModel> semanticModel)
        {
            // A dictionary of all recognised constructor parameters.
            Dictionary<Type, Func<object>> parameterTypes = new Dictionary<Type, Func<object>>
            {
                { typeof(ISettings), () => settings },
                { typeof(SemanticModel), semanticModel },
            };

            // Get a list of the type's constructors together with the constructor parameters types,
            // ordered by number of parameters descending.
            var ctors = (from c in type.GetConstructors()
                         select new
                         {
                             ConstructorInfo = c,
                             Parameters = c.GetParameters()
                         }).OrderByDescending(x => x.Parameters.Length).ToArray();

            // Get the first constructor in which we recognise all parameter types.
            var ctor = ctors.FirstOrDefault(x => x.Parameters.All(p => parameterTypes.Keys.Contains(p.ParameterType)));

            object[] parameters = ctor.Parameters.Select(x => parameterTypes[x.ParameterType]()).ToArray();

            return (RuleRewriter)ctor.ConstructorInfo.Invoke(parameters);
        }
        public DataRowKeyInfoHelper(Type type)
        {
            this.type = type;

            this.properties = type
                .GetProperties()
                .Select(p => new {
                    Property = p,
                    Attribute = p.GetCustomAttributes(false)
                        .OfType<DataRowPropertyAttribute>()
                        .SingleOrDefault()
                })
                .Where(x => x.Attribute != null)
                .OrderBy(x => x.Attribute.Index)
                .Select(x => x.Property)
                .ToArray();

            this.ctor = type
                .GetConstructors()
                .Single();

            this.isLarge = this.type
                .GetCustomAttributes(false)
                .OfType<LargeDataRowAttribute>()
                .Any();
        }
示例#3
0
        private ConstructorInfo GetConstructor(Type type)
        {
            ConstructorInfo constructor;
            if (constructors.TryGetValue(type, out constructor))
            {
                return constructor;
            }
            lock (syncHelper)
            {
                if (constructors.TryGetValue(type, out constructor))
                {
                    return constructor;
                }

                var candidates = type.GetConstructors().Where(c => c.GetCustomAttributes<InjectionAttribute>().Any());
                if (!candidates.Any())
                {
                    candidates = type.GetConstructors();
                }

                candidates = candidates.OrderByDescending(c => c.GetParameters().Count());
                constructor = candidates.FirstOrDefault();

                if (null == constructor)
                {
                    throw new ArgumentException("Cannot instantiate...", "type");
                }
                constructors[type] = constructor;
                return constructor;
            }
        }
        /// <summary>
        ///   Gets the given <paramref name="implementationType" />'s constructor that can be used by the
        ///   container to create that instance.
        /// </summary>
        /// <param name="serviceType">Type of the abstraction that is requested.</param>
        /// <param name="implementationType">Type of the implementation to find a suitable constructor for.</param>
        /// <returns>
        ///   The <see cref="T:System.Reflection.ConstructorInfo" />.
        /// </returns>
        /// <exception cref="T:SimpleInjector.ActivationException">Thrown when no suitable constructor could be found.</exception>
        public ConstructorInfo GetConstructor(Type serviceType, Type implementationType)
        {
            // note: this I want in the future to be pushed out to a rule overrides folder
            if (typeof(EntitiesContext).IsAssignableFrom(implementationType))
            {
                var defaultconstructor =
                    (from constructor in implementationType.GetConstructors()
                     where constructor.GetParameters().Count() == 0
                     select constructor).Take(1);

                if (defaultconstructor.Any()) return defaultconstructor.First();
            }

            if (serviceType.IsAssignableFrom(implementationType))
            {
                var longestConstructor =
                    (from constructor in implementationType.GetConstructors()
                     orderby constructor.GetParameters().Count() descending
                     select constructor).Take(1);

                if (longestConstructor.Any()) return longestConstructor.First();
            }

            // fall back to the container's default behavior.
            return _originalBehavior.GetConstructor(serviceType, implementationType);
        }
示例#5
0
        public static object Object(this DomainGenerator domaingenerator, Type type)
        {
            if (domaingenerator.constructionConventions.ContainsKey(type))
                return domaingenerator.constructionConventions[type]();

            var choiceConvention = domaingenerator.choiceConventions.FirstOrDefault(c => c.Type == type);
            if (choiceConvention != null)
                return choiceConvention.Possibilities.PickOne();

            var isPrimitiveGenerator = primitiveGenerators.Get(type);
            if (isPrimitiveGenerator != null)
            {
                return isPrimitiveGenerator.RandomAsObject();
            }

            var publicConstructors =
                type.GetConstructors(DomainGenerator.FlattenHierarchyBindingFlag);

            if (publicConstructors.Count() > 0)
            {
                var highestParameterCount = publicConstructors.Max(c => c.GetParameters().Count());
                var constructor = publicConstructors.First(c => c.GetParameters().Count() == highestParameterCount);
                return Construct(domaingenerator, constructor, highestParameterCount);
            }

            var allConstructors = type.GetConstructors(DomainGenerator.FlattenHierarchyBindingFlag);
            if (allConstructors.Count() > 0)
            {
                var highestParameterCount = allConstructors.Max(c => c.GetParameters().Count());
                var constructor = allConstructors.First(c => c.GetParameters().Count() == highestParameterCount);
                return Construct(domaingenerator, constructor, highestParameterCount);
            }
            return Activator.CreateInstance(type);
        }
示例#6
0
 public static void WarmInstanceConstructor(Type type)
 {
     if (!activators.ContainsKey(type))
     {
         var constructors = type.GetConstructors();
         if (constructors.Length == 1)
         {
             ConstructorInfo ctor = type.GetConstructors().First();
             activators.TryAdd(type, GetActivator(ctor));
         }
     }
 }
        public override ConstructorInfo GetConstructor(Type type)
        {
            var maxlen = type.GetConstructors().Max(x => x.GetParameters().Length);
            var candidates = type.GetConstructors()
                .Where(x => x.GetParameters().Length == maxlen)
                .ToArray();

            if (candidates.Length > 1)
                throw new DependencyConstructorException("Type {0} has at least two longest constructors", type.FullName);

            if (candidates.Length == 1)
                return candidates.First();

            return Next.GetConstructor(type);
        }
        static void Main(string[] args)
        {
            //Reflection
            //Reflect Type

            //typeDef
            System.Type _typeDef = typeof(ReflectionDemo.A);


            //Check Flags
            System.Reflection.MethodInfo[]      methods      = _typeDef.GetMethods();
            System.Reflection.ParameterInfo[]   parameters   = methods[0].GetParameters();
            System.Reflection.FieldInfo[]       feilds       = _typeDef.GetFields();
            System.Reflection.ConstructorInfo[] constructors = _typeDef.GetConstructors();
            //for (int i = 0; i < methods.Length; i++)
            //{
            //    Console.WriteLine(methods[i].Name);
            //}

            System.Reflection.MethodInfo _funMethodMetadata =
                _typeDef.GetMethod("Fun",
                                   System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            //Dynamic Invoke
            _funMethodMetadata.Invoke(new A(), null);

            Object obj = new A();

            System.Type _typeADef = obj.GetType();//returns metadata reference of object type
            _typeADef.GetMethod("Foo").Invoke(obj, null);

            System.Reflection.MethodInfo _concatMetadataRef = _typeADef.GetMethod("Concat");
            object result = _concatMetadataRef.Invoke(obj, new object[] { 10, "Hello" });
        }
示例#9
0
        private static GameCore GetGameCore(AppCore _app, string _appname)
        {
            System.Type ttype = typeof(GameCore);
            System.Reflection.ConstructorInfo[] constructorInfoArray = ttype.GetConstructors(System.Reflection.BindingFlags.Instance
                                                                                             | System.Reflection.BindingFlags.NonPublic
                                                                                             | System.Reflection.BindingFlags.Public);
            System.Reflection.ConstructorInfo noParameterConstructorInfo = null;

            foreach (System.Reflection.ConstructorInfo constructorInfo in constructorInfoArray)
            {
                System.Reflection.ParameterInfo[] parameterInfoArray = constructorInfo.GetParameters();
                if (2 == parameterInfoArray.Length)
                {
                    noParameterConstructorInfo = constructorInfo;
                    break;
                }
            }
            if (null == noParameterConstructorInfo)
            {
                throw new System.NotSupportedException("No constructor without 2 parameter");
            }

            object[] tparams = { _app, _appname };
            return((GameCore)noParameterConstructorInfo.Invoke(tparams));
        }
        /// <summary>
        /// Finds the constructor that takes the parameters.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param>
        /// <param name="types">The <see cref="IType"/> objects to use to find the appropriate constructor.</param>
        /// <returns>
        /// An <see cref="ConstructorInfo"/> that can be used to create the type with
        /// the specified parameters.
        /// </returns>
        /// <exception cref="InstantiationException">
        /// Thrown when no constructor with the correct signature can be found.
        /// </exception>
        public static ConstructorInfo GetConstructor(System.Type type, IType[] types)
        {
            ConstructorInfo[] candidates = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (ConstructorInfo constructor in candidates)
            {
                ParameterInfo[] parameters = constructor.GetParameters();

                if (parameters.Length == types.Length)
                {
                    bool found = true;

                    for (int j = 0; j < parameters.Length; j++)
                    {
                        bool ok = parameters[j].ParameterType.IsAssignableFrom(
                            types[j].ReturnedClass);

                        if (!ok)
                        {
                            found = false;
                            break;
                        }
                    }

                    if (found)
                    {
                        return(constructor);
                    }
                }
            }
            throw new InstantiationException("no appropriate constructor in class: ", null, type);
        }
示例#11
0
文件: Builder.cs 项目: ETLang/Gluon
        public void Merge(Struct ast, System.Type type)
        {
            var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToArray();

            foreach (var c in type.GetConstructors())
            {
                var args = c.GetParameters();

                if (args.Length == fields.Length)
                {
                    bool found = true;
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i].ParameterType != fields[i].FieldType)
                        {
                            found = false;
                        }
                    }
                    if (found)
                    {
                        ast.PredefinedFullConstructor = true;
                    }
                }
            }

            foreach (var field in fields)
            {
                ast.Fields.Add(Resolve(field));
            }
        }
        public Activator CreateActivator(Type type, out List<Type> dependencies)
        {
            dependencies = new List<Type>();

            ConstructorInfo constructorInfo = type.GetConstructors()[0];

            ParameterInfo[] parameters = constructorInfo.GetParameters();

            var method = new DynamicMethod("CreateInstance", typeof(object), new[] { typeof(object[]) });

            ILGenerator generator = method.GetILGenerator();

            for (int index = 0; index < parameters.Length; index++)
            {
                Type parameterType = parameters[index].ParameterType;

                dependencies.Add(parameterType);

                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, index);
                generator.Emit(OpCodes.Ldelem_Ref);
                generator.Emit(parameterType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, parameterType);
            }

            generator.Emit(OpCodes.Newobj, constructorInfo);
            generator.Emit(OpCodes.Ret);

            var activator = method.CreateDelegate(typeof(Activator)) as Activator;

            return activator;
        }
示例#13
0
        public QueryModelDescription(System.Type aModel, QueryModelAttribute aDescription)
        {
            if (aModel == null)
            {
                throw new NullReferenceException("QueryModelDescription: Model type can't be null");
            }
            if (aDescription == null)
            {
                throw new NullReferenceException("QueryModelDescription: Attribute must be specified");
            }

            foreach (ConstructorInfo info in aModel.GetConstructors())
            {
                if (info.GetParameters().Length == 1)
                {
                    if (TypeValidator.IsCompatible(info.GetParameters()[0].ParameterType, typeof(MappingsImplementor)) == true)
                    {
                        constructor = info;
                        break;
                    }
                }
            }

            if (constructor == null)
            {
                throw new NotImplementedException("QueryModelDescription: QueryImplementor needs public .ctor (MappingsImplementor)");
            }
            model      = aModel;
            definition = aDescription;
        }
        /// <summary>
        /// Verify the expectations on a message type.
        /// </summary>
        /// <param name="type">The message type to assert on.</param>
        private static void TestType(Type type)
        {
            // get the fields of the type
            FieldInfo[] fields = type.GetFields();

            // all fields must be public readonly
            Assert.IsTrue(fields.All(f => f.IsPublic && f.IsInitOnly),
                "All fields must be marked public readonly. Not conforming:  {0}",
                fields.Where(f => !(f.IsPublic && f.IsInitOnly)).Select(f => f.Name).ToArray());

            // get the constructors of the type
            ConstructorInfo[] constructors = type.GetConstructors();

            // the type must have exactly one constructor
            Assert.Count(1, constructors, "The message type has {0} constructors and must have exactly 1", constructors.Count());
            ConstructorInfo constructor = constructors.Single();

            // get the parameters of the constructor
            ParameterInfo[] parameters = constructor.GetParameters();

            // the parameter count must be exactly as the field count
            Assert.Count(fields.Count(), parameters,
                "The constructor parameter {0} count must be the same as the field count {1} .", parameters.Count(), fields.Count());

            // get the names of the fields
            IEnumerable<string> fieldNames = fields.Select(f => f.Name.ToLowerInvariant());

            // get the names of the constructor parameters
            IEnumerable<string> paramNames = parameters.Select(p => p.Name.ToLowerInvariant());

            // assert they are the same
            Assert.AreElementsEqualIgnoringOrder(fieldNames, paramNames);
        }
示例#15
0
        /// <summary>
        ///  通过DataRow 创建一个实体对象。
        /// </summary>
        /// <param name="drData"></param>
        /// <param name="targetObjType"></param>
        /// <returns></returns>
        public T CreateModelObject <T>(DataRow drData)
        {
            bool hashNullDeaultCst = false;

            System.Type targetObjType = typeof(T);
            System.Reflection.ConstructorInfo[] cons = targetObjType.GetConstructors();
            foreach (System.Reflection.ConstructorInfo cInfo in cons)
            {
                if (cInfo.GetParameters().Length == 0)
                {
                    hashNullDeaultCst = true;
                    break;
                }
            }

            if (!hashNullDeaultCst)
            {
                throw new MB.Util.APPException("通过DataRow 自动创建必须要有一个默认空的构造函数,请检查该类型是否已经定义。");
            }

            T targetObj = (T)System.Activator.CreateInstance(targetObjType);

            FillModelObject(targetObj, drData);
            return(targetObj);
        }
示例#16
0
 public System.Reflection.ConstructorInfo GetConstructorOf(System.String fullClassName)
 {
     System.Type clazz = classPool.GetClass(fullClassName);
     try
     {
         // Checks if exist a default constructor - with no parameters
         System.Reflection.ConstructorInfo constructor = clazz.GetConstructor(new System.Type[0]);
         return(constructor);
     }
     catch (System.MethodAccessException e)
     {
         // else take the constructer with the smaller number of parameters
         // and call it will null values
         // @TODO Put this inf oin cache !
         if (OdbConfiguration.IsDebugEnabled(LogId))
         {
             DLogger.Debug(clazz + " does not have default constructor! using a 'with parameter' constructor will null values");
         }
         System.Reflection.ConstructorInfo[] constructors = clazz.GetConstructors();
         int numberOfParameters   = 1000;
         int bestConstructorIndex = 0;
         for (int i = 0; i < constructors.Length; i++)
         {
             //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
             if (constructors[i].GetParameters().Length < numberOfParameters)
             {
                 bestConstructorIndex = i;
             }
         }
         System.Reflection.ConstructorInfo constructor = constructors[bestConstructorIndex];
         return(constructor);
     }
 }
示例#17
0
        public virtual object ResolveUnregistered(Type type)
        {
            var constructors = type.GetConstructors();
            foreach (var constructor in constructors)
            {
                try
                {
                    var parameters = constructor.GetParameters();
                    var parameterInstances = new List<object>();
                    foreach (var parameter in parameters)
                    {
                        var service = _container.Resolve(parameter.ParameterType);
                        if (service == null) throw new CoreException("Unkown dependency");
                        parameterInstances.Add(service);
                    }
                    return Activator.CreateInstance(type, parameterInstances.ToArray());
                }
                catch (CoreException)
                {

                }
            }

            throw new CoreException("No contructor was found that had all the dependencies satisfied.");
        }
 public ConstructorInfo[] FindConstructors(Type targetType)
 {
     return targetType.GetConstructors()
         .Where(x => x.IsPublic)
         .OrderByDescending(x => x.GetParameters().Count())
         .ToArray();
 }
        public override ConventionResult IsSatisfiedBy(Type type)
        {
            var constructors = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            // Note: only one constructor? it should be public.
            if (constructors.Count() == 1)
            {
                if (constructors.Single().IsPublic)
                {
                    return ConventionResult.Satisfied(type.FullName);
                }

                return ConventionResult.NotSatisfied(type.FullName, FailureMessage);
            }

            // Note: more than one constructor? the default constructor should be protected and the others public.
            var defaultConstructorIsProtected = constructors.Where(c => c.GetParameters().Any() == false).All(c => c.IsFamily);
            var allNonDefaultConstructorsArePublic = constructors.Where(c => c.GetParameters().Any()).All(c => c.IsPublic);

            if (defaultConstructorIsProtected && allNonDefaultConstructorsArePublic)
            {
                return ConventionResult.Satisfied(type.FullName);
            }

            return ConventionResult.NotSatisfied(type.FullName, FailureMessage);
        }
示例#20
0
        /// <summary>
        /// Creates a factory to instantiate a type using constructor service injection if possible.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Func<IServiceProvider, object> CreateFactory(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            ConstructorInfo[] constructors = type
                .GetConstructors()
                .Where(IsInjectable)
                .ToArray();

            if (constructors.Length == 1)
            {
                ParameterInfo[] parameters = constructors[0].GetParameters();
                return services =>
                {
                    var args = new object[parameters.Length];
                    for (int index = 0; index != parameters.Length; ++index)
                    {
                        args[index] = services.GetService(parameters[index].ParameterType);
                    }
                    return Activator.CreateInstance(type, args);
                };
            }
            return _ => Activator.CreateInstance(type);
        }
        // Creates a new dynamic type that is a subclassed type of baseType and also implements methods of the specified
        // interfaces. The base type must already have method signatures that implicitly implement the given
        // interfaces. The signatures of all public (e.g. not private / internal) constructors from the baseType
        // will be duplicated for the subclassed type and the new constructors made public.
        public static Type GenerateType(string dynamicTypeName, Type baseType, IEnumerable<Type> interfaceTypes)
        {
            var newType = _dynamicModule.DefineType(
                "System.Web.Mvc.{Dynamic}." + dynamicTypeName,
                TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Class,
                baseType);

            foreach (Type interfaceType in interfaceTypes)
            {
                newType.AddInterfaceImplementation(interfaceType);
                foreach (MethodInfo interfaceMethod in interfaceType.GetMethods())
                {
                    ImplementInterfaceMethod(newType, interfaceMethod);
                }
            }

            // generate new constructors for each accessible base constructor
            foreach (ConstructorInfo ctor in baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                switch (ctor.Attributes & MethodAttributes.MemberAccessMask)
                {
                    case MethodAttributes.Family:
                    case MethodAttributes.Public:
                    case MethodAttributes.FamORAssem:
                        ImplementConstructor(newType, ctor);
                        break;
                }
            }

            Type bakedType = newType.CreateType();
            return bakedType;
        }
        // Add the type to the list of creatable types
        public void Register(Type type)
        {
            if (type.IsEnum || constructors.ContainsKey(type))
                return;

            var constructor = type.GetConstructors().FirstOrDefault(x => x.GetParameters().Length == 0);
            if (constructor == null)
                throw new ArgumentException($"{type.FullName} does not have any accessible parameterless constructors.", nameof(type));

            constructors[type] = MethodFactory.CompileObjectConstructor(constructor);

            var attributes = type.GetCustomAttributes<SerializedNameAttribute>(false).ToArray();
            if (attributes.Length == 0)
            {
                remoteToLocalNames[type.FullName] = type;
            }
            else if (attributes.Count(x => x.Canonical) == 1)
            {
                foreach (var attribute in attributes)
                    RegisterAlias(type, attribute.SerializedName, attribute.Canonical);
            }
            else
            {
                throw new ArgumentException(
                    $"{type.FullName} has {attributes.Count(x => x.Canonical)} candidate names marked as canonical. only one can be canonical.",
                    nameof(type));
            }
        }
        private static bool CanHandleType(Type type)
        {
            if (type.IsValueType)
            {
                return true;
            }

            if (type.IsClass)
            {
                if (type.GetConstructors().Any(ci => !ci.GetParameters().Any()))
                {
                    return true;
                }

                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Types without default constructors aren't supported. Provide instance of type {0} explicitly", type.FullName));
            }

            if (type.IsGenericTypeDefinition)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Generic type definition can't be substituted. Provide explicit stub for {0}", type.FullName));
            }

            if (type.IsConstructedGenericType && !type.GetGenericArguments().All(t => t.IsPublic))
            {
                // NSubstitute can't construct proxy for an interface with non-public arguments,
                // but it is possible that generic definition interface will be satisfied, so skip it for now
                return false;
            }

            return true;
        }
示例#24
0
        public static Type GenerateType(string dynamicTypeName, Type baseType, Type interfaceType)
        {
            TypeBuilder newType = _dynamicModule.DefineType(
                "Xunit.{Dynamic}." + dynamicTypeName,
                TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Class,
                baseType
            );

            newType.AddInterfaceImplementation(interfaceType);

            foreach (MethodInfo interfaceMethod in interfaceType.GetMethods())
                ImplementInterfaceMethod(newType, interfaceMethod);

            foreach (ConstructorInfo ctor in baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                switch (ctor.Attributes & MethodAttributes.MemberAccessMask)
                {
                    case MethodAttributes.Family:
                    case MethodAttributes.Public:
                    case MethodAttributes.FamORAssem:
                        ImplementConstructor(newType, ctor);
                        break;
                }

            return newType.CreateType();
        }
示例#25
0
        /// <summary>
        /// Generates the specified number of POCO objects
        /// </summary>
        /// <param name="T">Specified POCO class type</param>
        public static object Generate(Type T)
        {
            // identify constructor parameters for the type
            ConstructorInfo[] cInfo = T.GetConstructors();

            // get parameters from the first constructor
            ParameterInfo[] cParams = cInfo[0].GetParameters();
            foreach (ParameterInfo cParam in cParams)
            {
                switch (cParam.ParameterType.ToString())
                {
                    case "System.Decimal":
                        // make random Decimal value
                        break;

                    case "System.DateTime":
                        // make random DateTime value
                        break;

                    case "System.String":
                        // make random string value
                        break;

                }
                if (cParam.ParameterType == typeof (string))
                {
                }
            }

            return null;
        }
        public static void Initialize(Type serviceProviderType, IMvxIoCProvider iocProvider)
        {
            if (MvxServiceProvider.Instance != null)
                throw new MvxException("Service registry already initialized!");

#if NETFX_CORE
            var serviceProviderConstructor = serviceProviderType.GetTypeInfo().DeclaredConstructors.FirstOrDefault();
#else
            var serviceProviderConstructor = serviceProviderType.GetConstructors().FirstOrDefault();
#endif
            if (serviceProviderConstructor == null)
                throw new MvxException("No Service Factory Constructor included in Assembly!");
            var serviceProviderObject = serviceProviderConstructor.Invoke(new object[] {});
            if (serviceProviderObject == null)
                throw new MvxException("Construction of Service Factory failed!");
            var serviceProviderSetup = serviceProviderObject as IMvxServiceProviderSetup;
            if (serviceProviderSetup == null)
                throw new MvxException(
                    "Constructed Service Factory does not support IMvxServiceProviderSetup - type " +
                    serviceProviderObject.GetType().FullName);

            serviceProviderSetup.Initialize(iocProvider);

            if (MvxServiceProvider.Instance == null)
                throw new MvxException("Service registry not initialized!");
        }
        public static Type GenerateType(Type baseType, IEnumerable<Type> interfaceTypes)
        {
            var newType = dynamicModule.DefineType(
                Prefix + "." + baseType.GetName(),
                TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Class,
                baseType);

            interfaceTypes.Each(interfaceType =>
            {
                newType.AddInterfaceImplementation(interfaceType);
                interfaceType.GetMethods().Each(method =>
                {
                    ImplementInterfaceMethod(newType, method);
                });
            });

            baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Each(constructor =>
            {
                switch (constructor.Attributes & MethodAttributes.MemberAccessMask)
                {
                    case MethodAttributes.Family:
                    case MethodAttributes.Public:
                    case MethodAttributes.FamORAssem:
                        ImplementConstructor(newType, constructor);
                        break;
                }
            });

            return newType.CreateType();
        }
示例#28
0
            static bool follows_constructor_convention(Type arg)
            {
                var greediest_contructor = arg.GetConstructors().First();

                return greediest_contructor.GetParameters().Count() == 1
                       && greediest_contructor.GetParameters().First().ParameterType.Equals(typeof (ContainerCoreService));
            }
        public bool TryLoad(Type viewModelType, IDictionary<string, string> parameters, out IMvxViewModel model)
        {
            model = null;
            var constructor = viewModelType
                .GetConstructors()
                .FirstOrDefault(c => c.GetParameters().All(p=> p.ParameterType == typeof(string)));

            if (constructor == null)
                return false;

            var invokeWith = new List<object>();
            foreach (var parameter in constructor.GetParameters())
            {
                string parameterValue = null;
                if (parameters == null ||
                    !parameters.TryGetValue(parameter.Name, out parameterValue))
                {
                    MvxTrace.Trace("Missing parameter in call to {0} - missing parameter {1} - asssuming null", viewModelType,
                                   parameter.Name);
                }
                invokeWith.Add(parameterValue);
            }

            model = Activator.CreateInstance(viewModelType, invokeWith.ToArray()) as IMvxViewModel;
            return (model != null);
        }
示例#30
0
        /// <summary>
        /// Finds the constructor that takes the parameters.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param>
        /// <param name="types">The <see cref="IType"/> objects to use to find the appropriate constructor.</param>
        /// <returns>
        /// An <see cref="ConstructorInfo"/> that can be used to create the type with
        /// the specified parameters.
        /// </returns>
        /// <exception cref="InstantiationException">
        /// Thrown when no constructor with the correct signature can be found.
        /// </exception>
        public static ConstructorInfo GetConstructor(System.Type type, IType[] types)
        {
            ConstructorInfo[] candidates = type.GetConstructors(AnyVisibilityInstance);

            foreach (ConstructorInfo constructor in candidates)
            {
                ParameterInfo[] parameters = constructor.GetParameters();

                if (parameters.Length == types.Length)
                {
                    bool found = true;

                    for (int j = 0; j < parameters.Length; j++)
                    {
                        bool ok = parameters[j].ParameterType.IsAssignableFrom(
                            types[j].ReturnedClass);

                        if (!ok)
                        {
                            found = false;
                            break;
                        }
                    }

                    if (found)
                    {
                        return(constructor);
                    }
                }
            }

            throw new InstantiationException(FormatConstructorNotFoundMessage(types), null, type);
        }
        private Func<IBackend> CreateBackendFactory(Type type, object[] args)
        {
            var constructors = type.GetConstructors();

            foreach (var ctor in constructors)
            {
                var parameters = ctor.GetParameters();
                var paramTypes = parameters.Select(i => i.ParameterType).ToArray();
                if (paramTypes.Length != args.Length)
                {
                    continue;
                }

                // Make sure the args all match up
                if (!paramTypes.Zip(args, TestArgForParameter)
                    .All(i => i))
                {
                    continue;
                }

                var paramExpr = parameters.Select(i => Expression.Parameter(i.ParameterType, i.Name)).ToArray();
                var callCtor = Expression.New(ctor, paramExpr);
                var createDelegate = Expression.Lambda<Func<IBackend>>(callCtor, paramExpr).Compile();
                return createDelegate;
            }

            return null;
        }
示例#32
0
        public static object CreateAnonymous(this DbDataReader reader, Type type, QueryMap queryMap)
        {
            var ctor = type.GetConstructors()[0];
            var pp = ctor.GetParameters();
            var args = new object[pp.Length];
            QueryMap map2 = null;
            for (var i = 0; i < args.Length; i++)
            {
                var name = pp[i].Name;
                var map = queryMap.FirstOrDefault(_ => _.MemberPath.Sections[0] == name);
                if (map.MemberPath.Length == 1)
                {
                    args[i] = reader[map.ColumnAlias];
                }
                else
                {
                    if (map2 == null)
                    {
                        map2 = queryMap.LeftShift(1);
                    }
                    args[i] = Create(reader, pp[i].ParameterType, map2);
                }
            }

            return ctor.Invoke(args.ToArray());
        }
 public ConstructorInfo Find(Type pluggedType)
 {
     return pluggedType
         .GetConstructors()
         .OrderByDescending(x => x.GetParameters().Count())
         .FirstOrDefault();
 }
		public object Create(Type type)
		{
			ConstructorDefinition ctorDefinition;
			lock (readWriteLock)
			{
				if (!objectActivatorMap.TryGetValue(type, out ctorDefinition))
				{
					var largestConstructor = type.GetConstructors()
						.OrderByDescending(x => x.GetParameters().Length).First();

					var ctorValues = new List<object>();
					foreach (var parameterInfo in largestConstructor.GetParameters())
					{
						var ctorValue = factoryProvider.Resolve(parameterInfo.ParameterType)
						                ?? ReflectionUtils.GetDefaultValue(parameterInfo.ParameterType);

						ctorValues.Add(ctorValue);
					}

					ctorDefinition = new ConstructorDefinition(
						ctorValues.ToArray(), GetActivator(largestConstructor));

					objectActivatorMap[type] = ctorDefinition;
				}
			}

			return ctorDefinition.Create();
		}
        public ConstructorInfo ChooseConstructor(Type t)
        {
            Guard.ArgumentNotNull(t, "AttributeBasedConstructorChooser requires a Type instance.");

            ConstructorInfo[] ctors = t.GetConstructors();
            if (ctors.Length == 1)
            {
                return ctors[0];
            }

            bool foundInjectionConstructor = false;
            ConstructorInfo injectionConstructor = null;

            if (ctors.Length > 0)
            {
                injectionConstructor = ctors[0];
            }

            foreach (ConstructorInfo ctor in ctors)
            {
                if (Attribute.IsDefined(ctor, typeof (InjectionConstructorAttribute)))
                {
                    if (foundInjectionConstructor)
                    {
                        // Multiple injection constructors are an error
                        throw new InvalidAttributeException(string.Format(CultureInfo.CurrentCulture,
                                                                          "Type {0} has multiple injection constructors", t));
                    }
                    injectionConstructor = ctor;
                    foundInjectionConstructor = true;
                }
            }

            return injectionConstructor;
        }
示例#36
0
 private static object CreateSubscriber(Type subscriberType)
 {
     var constructor = subscriberType.GetConstructors()[0];
     var parameterValues = new List<object>();
     constructor.GetParameters().ForEach(parameterInfo => parameterValues.Add(GetValueForType(parameterInfo.ParameterType)));
     return constructor.Invoke(parameterValues.ToArray());
 }
示例#37
0
        /// <summary>
        /// Creates a new ClrStaticTypeWrapper object.
        /// </summary>
        /// <param name="engine"> The associated script engine. </param>
        /// <param name="type"> The CLR type to wrap. </param>
        /// <param name="flags"> <c>BindingFlags.Static</c> to populate static methods;
        /// <c>BindingFlags.Instance</c> to populate instance methods. </param>
        private ClrStaticTypeWrapper(ScriptEngine engine, Type type)
            : base(engine, GetPrototypeObject(engine, type))
        {
            this.WrappedType = type;

            // Pick up the public constructors, if any.
            var constructors = type.GetConstructors();
            if (constructors.Length > 0)
                this.constructBinder = new ClrBinder(constructors);
            else
            {
                // The built-in primitive types do not have constructors, but we still want to
                // allow their construction since there is no way to construct them otherwise.
                // Pretend that a constructor does exist.
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.Int32:
                        this.constructBinder = new ClrBinder(ReflectionHelpers.Convert_ToInt32_Double);
                        break;
                }
            }

            this.FastSetProperty("name", type.Name);
            if (this.constructBinder != null)
                this.FastSetProperty("length", this.constructBinder.FunctionLength);

            // Populate the fields, properties and methods.
            PopulateMembers(this, type, BindingFlags.Static);
        }
示例#38
0
        /// <summary>
        /// Selects the constructor marked with <see cref="ConstructAttribute"/>
        /// or with the minimum amount of parameters.
        /// </summary>
        /// <param name="type">Type from which reflection will be resolved.</param>
        /// <returns>The constructor.</returns>
        protected ConstructorInfo ResolveConstructor(Type type)
        {
            var constructors = type.GetConstructors(
                BindingFlags.FlattenHierarchy |
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.InvokeMethod);

            if (constructors.Length == 0) {
                return null;
            }

            if (constructors.Length == 1) {
                return constructors[0];
            }

            ConstructorInfo shortestConstructor = null;
            for (int i = 0, length = 0, shortestLength = int.MaxValue; i < constructors.Length; i++) {
                var constructor = constructors[i];

                object[] attributes = constructor.GetCustomAttributes(typeof(Construct), true);

                if (attributes.Length > 0) {
                    return constructor;
                }

                length = constructor.GetParameters().Length;
                if (length < shortestLength) {
                    shortestLength = length;
                    shortestConstructor = constructor;
                }
            }

            return shortestConstructor;
        }
示例#39
0
        public void Build(ClassType classType, System.Type type)
        {
            base.Build(classType, type, (x) => x.IsPublic && !x.IsStatic, (x) => x.IsPublic && !x.IsStatic);

            var constrInfo = type.GetConstructors().Where(x => x.IsPublic && !x.IsStatic);

            foreach (var item in constrInfo)
            {
                BuildConstructor(classType, item);
            }
        }
示例#40
0
 /// <summary>
 /// Creates new configuration object instance
 /// </summary>
 /// <returns>
 /// Returns instance of the new configuration object <see cref="System.Object"/>
 /// </returns>
 public object CreateConfigTypeInstance()
 {
     foreach (ConstructorInfo cons in SerializableObjectType.GetConstructors())
     {
         if (cons.GetParameters().Length == 0)
         {
             return(cons.Invoke(null));
         }
     }
     return(null);
 }
示例#41
0
        public static ObjectActivator GetActivator(this System.Type me, System.Type attributeType)
        {
            if (!attributeType.IsSubclassOf(typeof(Attribute)))
            {
                return(GetActivator(me, new[] { attributeType }));
            }

            var ctor = me.GetConstructors().First(c => c.CustomAttributes.Any(a => a.AttributeType == attributeType));

            return(GenerateObjectActivator(ctor));
        }
示例#42
0
        protected override IController GetControllerInstance(
            System.Web.Routing.RequestContext requestContext,
            System.Type controllerType)
        {
            var res = (from ctorInfo in controllerType.GetConstructors()
                       let paramstype = ctorInfo.GetParameters().Select(p => p.ParameterType)
                                        where paramstype.Except(_bindings.Keys).Count() == 0
                                        select(IController) ctorInfo.Invoke(paramstype.Select(t => _bindings[t]).ToArray()));

            return(res.Count() != 0 ?
                   res.First() :
                   base.GetControllerInstance(requestContext, controllerType));
        }
示例#43
0
        public void OutputToFile(String fn)
        {
            System.IO.FileStream      fs = new System.IO.FileStream(fn, System.IO.FileMode.Create);
            System.IO.StreamWriter    st = new System.IO.StreamWriter(fs, System.Text.Encoding.ASCII);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            if (!m_type.IsInterface && m_type.BaseType.FullName == "System.Enum")
            {
                /* enumerations are mapped onto Haskell data types. */
                System.String sep = " = ";
                sb.AppendFormat("data {0}Ty", m_type.Name);
                sb.Append(System.Environment.NewLine);
                foreach (System.Reflection.MemberInfo mem in m_members)
                {
                    if (mem.Name != "value__")
                    {
                        sb.Append(sep);
                        OutputField(sb, mem);
                        sb.Append(System.Environment.NewLine);
                        sep = " | ";
                    }
                }
                sb.AppendFormat("  deriving ( Enum, Show, Read ){0}", System.Environment.NewLine);
                // Emit functions for converting betw alg type and object type.
                AddImport("IOExts");
                AddImport("Dotnet.System.Type");
                AddImport("Dotnet.System.Enum");
                sb.AppendFormat("to{0} :: {0}Ty -> {0} (){1}", m_type.Name, System.Environment.NewLine);
                sb.AppendFormat("to{0} tag = IOExts.unsafePerformIO (Dotnet.System.Enum.parse (IOExts.unsafePerformIO (Dotnet.System.Type.getType \"{1}\")) (show tag)){2}", m_type.Name, m_type.AssemblyQualifiedName, System.Environment.NewLine);
                sb.Append(System.Environment.NewLine);
                sb.AppendFormat("from{0} :: {0} () -> {0}Ty{1}", m_type.Name, System.Environment.NewLine);
                sb.AppendFormat("from{0} obj = IOExts.unsafePerformIO (toString obj >>= return.read)", m_type.Name);
                sb.Append(System.Environment.NewLine);
            }
            else
            {
                foreach (System.Reflection.MemberInfo mem in m_members)
                {
                    OutputMember(sb, mem);
                }
                foreach (System.Reflection.ConstructorInfo ci in m_type.GetConstructors())
                {
                    OutputCtor(sb, ci);
                }
            }
            OutputHeader(st);
            st.WriteLine(sb.ToString());
            st.Flush();
            st.Close();
            fs.Close();
        }
示例#44
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Paladin newPaladin = new Paladin()
            {
                Height = 5.6,
                Stones = 300
            };

            Warlock newWarlock = new Warlock()
            {
                Height = 5.6,
                Stones = 250
            };

            ICharacterClass convertedCharacter = CharacterClassConversion.ConvertCharacterClass(
                newPaladin,
                CharacterClasses.WARLOCK);

            System.Type    type    = convertedCharacter.GetType();
            PropertyInfo[] myArray = type.GetProperties();

            Console.Write(String.Format("Printing Properties for Object {0} and the namespace {1} \n", type.Name, type.Namespace));
            foreach (PropertyInfo myParam in myArray)
            {
                Console.Write(myParam.Name + "\n");
            }

            ConstructorInfo[] constructorInfo = type.GetConstructors();

            Console.Write("Printing constructors for {0} \n", type.Name);
            foreach (ConstructorInfo constructor in constructorInfo)
            {
                Console.Write(string.Format("{0} \n", constructor));
            }

            MethodInfo[] methodInfo = type.GetMethods();

            Console.Write("Pringing methods for {0} \n", type.Name);
            foreach (MethodInfo method in methodInfo)
            {
                Console.Write(string.Format("{0} \n", method));
            }

            Console.Write("Pringing custom attributes for {0} \n", type.Name);
            foreach (Attribute attribute in type.GetCustomAttributes(true))
            {
                Console.Write(string.Format("{0} \n", attribute));
            }
        }
        public IReadOnlyList <string> GetMostDescriptiveConstructor(System.Type type)
        {
            var constructors = type.GetConstructors();

            if (!constructors.Any())
            {
                return(new List <string>());
            }

            Array.Sort(constructors,
                       (info, constructorInfo) => info.GetParameters().Length - constructorInfo.GetParameters().Length);

            return(constructors.Last().GetParameters().Select(x => x.Name).ToList());
        }
示例#46
0
            public static Class From(System.Type type)
            {
                Logger.Info($"Creating class from type: {type.FullName}");
                var obj = new Class();

                obj.Name = type.FullName;

                obj.IsInterface = type.IsInterface;
                obj.IsAbstract  = type.IsAbstract;

                if (type.BaseType != null)
                {
                    obj.Parent = TypeRef.From(type.BaseType);
                }

                foreach (var iface in type.GetInterfaces())
                {
                    obj.Interfaces.Add(TypeRef.From(iface));
                }

                // No to pass BindingFlags, already gets only the public constructors by default
                foreach (var ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    obj.Constructors.Add(Function.From(ctor));
                }

                // FIXME Do we need to list static methods too?
                foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    // Skip anonymous property accessors (get_Name)
                    if (!method.IsSpecialName)
                    {
                        obj.Methods.Add(Function.From(method));
                    }
                }

                foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    obj.Properties.Add(Property.From(property));
                }

                foreach (var evt in type.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    obj.Events.Add(Event.From(evt));
                }

                return(obj);
            }
示例#47
0
        /// <summary>
        /// 查看类中的构造方法
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string oneString = "newtype";

            System.Type       t  = oneString.GetType();
            ConstructorInfo[] ci = t.GetConstructors();    //获得类的所有构造函数
            foreach (var item in ci)                       //遍历构造函数
            {
                ParameterInfo[] pi = item.GetParameters(); //取出每个构造函数的所有参数
                foreach (var i in pi)                      //遍历并打印构造函数的参数
                {
                    Console.WriteLine(i.ParameterType.ToString() + "" + i.Name + ",");
                }
            }
            Console.ReadKey();
        }
示例#48
0
        public void Build(GenericTemplate templateType, System.Type type)
        {
            var methods = type.GetMethods().Where(x => x.IsPublic && !x.IsStatic);

            foreach (var method in methods)
            {
                BuildMethod(templateType, method);
            }

            var constrInfo = type.GetConstructors().Where(x => x.IsPublic && !x.IsStatic);

            foreach (var item in constrInfo)
            {
                BuildConstructor(templateType, item);
            }
        }
示例#49
0
 /// <summary>Creates the repition</summary>
 /// <param name="rep">the number representing which repition
 /// </param>
 private Repeatable createRep(int rep)
 {
     try
     {
         System.Reflection.ConstructorInfo theCon = repType.GetConstructors()[0];
         Repeatable thisRep = (Repeatable)theCon.Invoke(new System.Object[] { underlyingObject, (System.Int32)rep });
         return(thisRep);
     }
     catch (System.Reflection.TargetInvocationException e)
     {
         throw new ConformanceError("Error creating underlying repetition. This is a bug.\nError is: " + e.ToString() + "\n" + e.InnerException.Message);
     }
     catch (System.Exception e)
     {
         throw new ConformanceError("Error creating underlying repetition. This is a bug. Error is: " + e.ToString());
     }
 }
示例#50
0
        public static Delegate <T> Compile <T>(System.Type type)
        {
            // Get constructor information?
            ConstructorInfo[] constructors = type.GetConstructors();

            // Is there at least 1?
            if (constructors.Length > 0)
            {
                // Get our one constructor.
                ConstructorInfo constructor = constructors[0];

                // Yes, does this constructor take some parameters?
                ParameterInfo[] paramsInfo = constructor.GetParameters();

                if (paramsInfo.Length > 0)
                {
                    // Create a single param of type object[].
                    ParameterExpression param = Expression.Parameter(typeof(object[]), "args");

                    // Pick each arg from the params array and create a typed expression of them.
                    Expression[] argsExpressions = new Expression[paramsInfo.Length];

                    for (int i = 0; i < paramsInfo.Length; i++)
                    {
                        Expression index            = Expression.Constant(i);
                        Type       paramType        = paramsInfo[i].ParameterType;
                        Expression paramAccessorExp = Expression.ArrayIndex(param, index);
                        Expression paramCastExp     = Expression.Convert(paramAccessorExp, paramType);
                        argsExpressions[i] = paramCastExp;
                    }

                    // Make a NewExpression that calls the constructor with the args we just created.
                    NewExpression newExpression = Expression.New(constructor, argsExpressions);

                    // Create a lambda with the NewExpression as body and our param object[] as arg.
                    LambdaExpression lambda = Expression.Lambda(typeof(Delegate <T>), newExpression, param);

                    // Compile it
                    Delegate <T> compiled = (Delegate <T>)lambda.Compile();
                    return(compiled);
                }
            }
            Common.Log.Logger.Fatal(string.Format("[Constructor::Compile] No Have Constructors. DelegateType : {0}, Instance Type : {1}", typeof(Delegate <T>).ToString(), type.ToString()));
            return(null);
        }
示例#51
0
        public static object InstantiateClassByType(System.Type type)
        {
            object obj = null;

            //cant call the entry method if the assembly is null
            ConstructorInfo[] constructors = type.GetConstructors();

            foreach (ConstructorInfo constructor in constructors)
            {
                if (constructor.GetParameters().Length == 0)
                {
                    obj = constructor.Invoke(BindingFlags.CreateInstance, null, new object[] {}, null);
                    break;
                }
            }

            return(obj);
        }
示例#52
0
        static StackObject *GetConstructors_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags) typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetConstructors(@bindingAttr);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
        public object CreateInstance(System.Type type)
        {
            try
            {
                return(System.Activator.CreateInstance(type));
            }
            catch (Exception e)
            {
                try
                {
                    var constructors = type.GetConstructors();

                    if (constructors.Length != 1)
                    {
                        throw;
                    }

                    var constructor = constructors[0];

                    var parameters = constructor.GetParameters();

                    try
                    {
                        return(constructor.Invoke(BindingFlags.OptionalParamBinding |
                                                  BindingFlags.InvokeMethod |
                                                  BindingFlags.CreateInstance,
                                                  null,
                                                  GetTypeMissingArray(parameters.Length),
                                                  CultureInfo.InvariantCulture));
                    }
                    catch
                    {
                        throw e;
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);

                    throw;
                }
            }
        }
示例#54
0
        //------------------------------------------------------------------------------
        public static Type Create(System.Type aNative)
        {
            var type = new Type();

            type.Name      = aNative.Name;
            type.FullName  = aNative.FullName;
            type.Namespace = aNative.Namespace;

            foreach (var ctor in aNative.GetConstructors())
            {
                type.Constructors.Add(Constructor.Create(ctor));
            }

            foreach (var method in aNative.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                type.Methods.Add(Method.Create(method));
            }

            return(type);
        }
示例#55
0
        /// <summary>
        /// Creates an instance of a received Type
        /// </summary>
        /// <param name="classType">The Type of the new class instance to return</param>
        /// <returns>An Object containing the new instance</returns>
        public static System.Object CreateNewInstance(System.Type classType)
        {
            System.Reflection.ConstructorInfo[] constructors = classType.GetConstructors();

            if (constructors.Length == 0)
            {
                return(null);
            }

            System.Reflection.ParameterInfo[] firstConstructor = constructors[0].GetParameters();
            int countParams = firstConstructor.Length;

            System.Type[] constructor = new System.Type[countParams];
            for (int i = 0; i < countParams; i++)
            {
                constructor[i] = firstConstructor[i].ParameterType;
            }

            return(classType.GetConstructor(constructor).Invoke(new System.Object[] {}));
        }
示例#56
0
        private static ISQLExceptionConverter ConstructConverter(string converterClassName, IViolatedConstraintNameExtracter violatedConstraintNameExtracter)
        {
            try
            {
                log.Debug("Attempting to construct instance of specified SQLExceptionConverter [" + converterClassName + "]");
                System.Type converterClass = ReflectHelper.ClassForName(converterClassName);

                // First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param...
                ConstructorInfo[] ctors = converterClass.GetConstructors(ReflectHelper.AnyVisibilityInstance);
                foreach (ConstructorInfo ctor in ctors)
                {
                    ParameterInfo[] parameters = ctor.GetParameters();

                    if (parameters == null || parameters.Length != 1)
                    {
                        continue;
                    }

                    if (typeof(IViolatedConstraintNameExtracter).IsAssignableFrom(parameters[0].ParameterType))
                    {
                        try
                        {
                            return((ISQLExceptionConverter)ctor.Invoke(new object[] { violatedConstraintNameExtracter }));
                        }
                        catch (Exception)
                        {
                            // eat it and try next
                        }
                    }
                }

                // Otherwise, try to use the no-arg constructor
                return((ISQLExceptionConverter)Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(converterClass));
            }
            catch (Exception t)
            {
                log.Warn("Unable to construct instance of specified SQLExceptionConverter", t);
            }

            return(null);
        }
示例#57
0
 /// <summary>
 /// Resolves constructor in subclassed DataRow class
 /// Constructor that has to be exposed is
 ///   ctor(DataRowBuilder)
 /// </summary>
 private void InitRowActivator()
 {
     System.Type       t            = typeof(T);
     ConstructorInfo[] constructors = t.GetConstructors();
     foreach (ConstructorInfo ci in constructors)
     {
         ParameterInfo[] pinfos = ci.GetParameters();
         if (pinfos != null)
         {
             if (pinfos.Length == 1)
             {
                 if (pinfos[0].ParameterType == typeof(DataRowBuilder))
                 {
                     cons = ci;
                     return;
                 }
             }
         }
     }
     throw new ExceptionInheritedDataRowMissingConstructor(typeof(T));
 }
示例#58
0
    public static object StringToObject(string current, System.Type type)
    {
        current = current.Replace("(", "").Replace(")", "");
        var split = current.Split(new string[] { "," }, System.StringSplitOptions.None);

        var actual_parameters = new object[split.Length];
        var constructors      = type.GetConstructors();

        for (int i = 0; i < constructors.Length; i++)
        {
            var formal_parameters = constructors[i].GetParameters();
            if (formal_parameters.Length == actual_parameters.Length)
            {
                for (int j = 0; j < formal_parameters.Length; j++)
                {
                    actual_parameters[j] = ConvertObject(split[j], formal_parameters[j].ParameterType);
                }
            }
        }
        return(System.Activator.CreateInstance(type, actual_parameters));
    }
示例#59
0
        // Get only public methods, or public/protected if type is not sealed
        public static ConstructorInfo[] GetConstructors(System.Type monoType)
        {
            ConstructorInfo[]      constructorInfos = monoType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            List <ConstructorInfo> finalInfos       = new List <ConstructorInfo>();

            foreach (ConstructorInfo constructorInfo in constructorInfos)
            {
                if (constructorInfo.IsPublic || (!monoType.IsSealed && constructorInfo.IsFamily))
                {
                    finalInfos.Add(constructorInfo);
                }
                else
                {
                    // Also add no param constructor
                    ParameterInfo[] parms = constructorInfo.GetParameters();
                    if (parms.Length == 0)
                    {
                        finalInfos.Add(constructorInfo);
                    }
                }
            }
            return(finalInfos.ToArray());
        }
示例#60
0
 private static System.Xml.XmlNode MakeTypeNode(System.Type type, System.Xml.XmlDocument ownerdoc)
 {
     System.Xml.XmlNode nodeCategory;
     System.Xml.XmlNode nodeType;
     nodeType     = Utility.xmlHelpers.NewElement(ownerdoc, "Type", type.Name);
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "Constructors"));
     foreach (System.Reflection.ConstructorInfo meminfo in type.GetConstructors())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakeMethodNode(meminfo, ownerdoc, false));
     }
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "Methods"));
     foreach (System.Reflection.MethodInfo meminfo in type.GetMethods())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakeMethodNode(meminfo, ownerdoc, true));
     }
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "Properties"));
     foreach (System.Reflection.PropertyInfo meminfo in type.GetProperties())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakePropertyNode(meminfo, ownerdoc));
     }
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "NestedTypes"));
     foreach (System.Type innerType in type.GetNestedTypes())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakeTypeNode(innerType, ownerdoc));
     }
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "Fields"));
     foreach (System.Reflection.FieldInfo memberInfo in type.GetFields())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakeFieldNode(memberInfo, ownerdoc));
     }
     nodeCategory = nodeType.AppendChild(Utility.xmlHelpers.NewElement(ownerdoc, "Category", "Events"));
     foreach (System.Type innerType in type.GetNestedTypes())
     {
         Utility.xmlHelpers.AppendIfExists(nodeCategory, MakeTypeNode(innerType, ownerdoc));
     }
     return(nodeType);
 }