当前位置: 首页>>代码示例>>C#>>正文


C# Type.GetConstructors方法代码示例

本文整理汇总了C#中System.Type.GetConstructors方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetConstructors方法的具体用法?C# Type.GetConstructors怎么用?C# Type.GetConstructors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Type的用法示例。


在下文中一共展示了Type.GetConstructors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Create

        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);
        }
开发者ID:grokys,项目名称:StyleCopMagic,代码行数:25,代码来源:RuleRewriterFactory.cs

示例2: DataRowKeyInfoHelper

        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();
        }
开发者ID:DeadlyEmbrace,项目名称:effort,代码行数:26,代码来源:DataRowKeyInfoHelper.cs

示例3: Object

        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);
        }
开发者ID:Bunk,项目名称:QuickGenerate,代码行数:34,代码来源:Create.cs

示例4: GetConstructor

        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;
            }
        }
开发者ID:jiangjinnan,项目名称:Dora,代码行数:31,代码来源:ReflectedBuilder.cs

示例5: GetConstructor

        /// <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);
        }
开发者ID:rhillaardvark,项目名称:chocolatey.org,代码行数:36,代码来源:SimpleInjectorContainerResolutionBehavior.cs

示例6: WarmInstanceConstructor

 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));
         }
     }
 }
开发者ID:Elders,项目名称:Experiments,代码行数:12,代码来源:Program.cs

示例7: GetConstructor

        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);
        }
开发者ID:krzychu,项目名称:DependencyInjectionEngine,代码行数:15,代码来源:LongestConstructorResolver.cs

示例8: GenerateType

        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();
        }
开发者ID:vialpando09,项目名称:RallyPortal2,代码行数:30,代码来源:DynamicTypeBuilder.cs

示例9: CreateSubscriber

 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());
 }
开发者ID:jiguixin,项目名称:MyLibrary,代码行数:7,代码来源:EventPublisher.cs

示例10: GenerateType

        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();
        }
开发者ID:JoB70,项目名称:xunit,代码行数:25,代码来源:DynamicTypeGenerator.cs

示例11: TestType

        /// <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);
        }
开发者ID:james-wu,项目名称:CQRSEventSourcingSample,代码行数:37,代码来源:MessagesSerializationTests.cs

示例12: ResolveConstructor

        /// <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;
        }
开发者ID:lmlynik,项目名称:cardgame,代码行数:41,代码来源:ReflectionFactory.cs

示例13: ResolveUnregistered

        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.");
        }
开发者ID:qhme,项目名称:OrchardLite,代码行数:25,代码来源:OrchardValidatorFactory.cs

示例14: GenerateType

        // 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;
        }
开发者ID:austinvernsonger,项目名称:ServiceStack,代码行数:36,代码来源:DynamicTypeGenerator+.cs

示例15: CreateAnonymous

        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());
        }
开发者ID:DzmitrySo,项目名称:sqLinq,代码行数:26,代码来源:DataReaderExtensions.cs


注:本文中的System.Type.GetConstructors方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。