System.Type.GetConstructors()

Here are the examples of the csharp api System.Type.GetConstructors() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

629 Examples 7

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public ConstructorInfo FindConstructor(Type csharpType)
        {
            var constructor = csharpType.GetConstructor(Type.EmptyTypes);
            if (constructor == null)
            {
                var constructors = csharpType.GetConstructors();
                constructor = constructors.Where(a => a.GetParameters().Length == constructors.Max(s => s.GetParameters().Length)).FirstOrDefault();
            }
            return constructor;
        }

19 View Source File : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v

public static Type CreateType(Type interfaceType)
        {
            try
            {
                TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);

                List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();

                List<MethodInfo> propertyInfos = new List<MethodInfo>();

                foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
                {
                    Type propType = prop.PropertyType;

                    PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);

                    MethodInfo iGetter = prop.GetMethod;
                    MethodInfo iSetter = prop.SetMethod;
                    if (iGetter != null)
                    {
                        propertyInfos.Add(iGetter);
                    }

                    if (iSetter != null)
                    {
                        propertyInfos.Add(iSetter);
                    }

                    if (prop.Name == "Item")
                    {
                        if (iGetter != null)
                        {
                            MethodAttributes accessor = iGetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetGetMethod(methBuilder);
                        }
                        if (iSetter != null)
                        {
                            MethodAttributes accessor = iSetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetSetMethod(methBuilder);
                        }
                        continue;
                    }


                    Func<FieldInfo> getBackingField;
                    {
                        FieldInfo backingField = null;
                        getBackingField =
                            () =>
                            {
                                if (backingField == null)
                                {
                                    backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
                                }

                                return backingField;
                            };
                    }

                    if (iGetter != null)
                    {
                        MethodAttributes accessor = iGetter.Attributes;
                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
                        ILGenerator il = methBuilder.GetILGenerator();
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldfld, getBackingField());
                        il.Emit(OpCodes.Ret);
                        propBuilder.SetGetMethod(methBuilder);
                    }

                    if (iGetter != null || iSetter != null)
                    {
                        MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
                        string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;

                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
                        ILGenerator il = methBuilder.GetILGenerator();

                        if (iGetter != null)
                        {
                            il.Emit(OpCodes.Ldarg_0);
                            il.Emit(OpCodes.Ldarg_1);
                            il.Emit(OpCodes.Stfld, getBackingField());
                            il.Emit(OpCodes.Ret);
                        }
                        else
                        {
                            il.Emit(OpCodes.Ret);
                        }

                        propBuilder.SetSetMethod(methBuilder);
                    }
                }

                foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
                {
                    MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
                    if (method.IsGenericMethod)
                    {
                        methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
                    }
                    ILGenerator il = methBuilder.GetILGenerator();
                    il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                    il.Emit(OpCodes.Throw);

                    typeBuilder.DefineMethodOverride(methBuilder, method);
                }

                return typeBuilder.CreateTypeInfo();
            }
            catch
            {
                throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
            }
        }

19 View Source File : TypeUtils.cs
License : MIT License
Project Creator : 1996v

public static ConstructorInfo GetDefaultNoArgCtorOrAppointTypeCtor(this Type type, Type ctorParaTypes = null)
        {
            foreach (ConstructorInfo ctor in type.GetConstructors())
            {
                ParameterInfo[] ctorParas = ctor.GetParameters();
                if (ctorParas.Length == 0)
                {
                    return ctor;//no args
                }

                if (ctorParaTypes != null && ctorParas.Length == 1)
                {
                    if (ctorParas[0].ParameterType == ctorParaTypes)
                    {
                        return ctor;
                    }
                }
            }
            return null;
        }

19 View Source File : TypeUtils.cs
License : MIT License
Project Creator : 1996v

public static ConstructorInfo GetAppointTypeCtor(this Type type, Type ctorParaType)
        {
            foreach (ConstructorInfo ctor in type.GetConstructors())
            {
                ParameterInfo[] ctorParas = ctor.GetParameters();
                if (ctorParas.Length == 1)
                {
                    if (ctorParas[0].ParameterType == ctorParaType)
                    {
                        return ctor;
                    }
                }
            }
            return null;
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

private static bool TryGetConstructorInfo(Type targetType, Type itemType, bool isFindEmptyCtor, out ConstructorInfo constructor)
        {
            constructor = null;
            foreach (ConstructorInfo item in targetType.GetConstructors())
            {
                ParameterInfo[] paras = item.GetParameters();

                if (isFindEmptyCtor)
                {
                    if (paras.Length == 0)
                    {
                        constructor = item;
                        return true;
                    }
                }

                if (constructor != null)
                {
                    continue;
                }

                if (paras.Length == 1)
                {
                    Type ctorArgType = paras[0].ParameterType;
                    if (targetType == ctorArgType)
                    {
                        continue;
                    }

                    if (
                        (TypeIsArray(ctorArgType, out int rank, out Type eleType) &&
                        rank == 1 && eleType == itemType
                        ) ||
                       (TypeIsCollection(ctorArgType, out ConstructorInfo a, out eleType, out bool c, out bool d, out bool e, out bool f) &&
                       eleType == itemType)
                        )
                    {
                        constructor = item;
                        if (!isFindEmptyCtor)
                        {
                            return true;
                        }
                    }
                }
            }
            return constructor != null;
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

private static bool TryGetConstructorInfo(Type targetType, Type genericKeyType, Type genericValueType, bool isFindEmptyCtor, out ConstructorInfo constructor)
        {
            constructor = null;
            foreach (ConstructorInfo item in targetType.GetConstructors())
            {
                ParameterInfo[] paras = item.GetParameters();

                if (isFindEmptyCtor)
                {
                    if (paras.Length == 0)
                    {
                        constructor = item;
                        return true;
                    }
                }

                if (constructor != null)
                {
                    continue;
                }

                if (paras.Length == 1)
                {
                    Type ctorArgType = paras[0].ParameterType;
                    if (targetType == ctorArgType)
                    {
                        continue;
                    }

                    if (TypeIsDictionary(ctorArgType, out ConstructorInfo cons, out bool tIsGener, out Type generTypeDefine, out Type generKeyType, out Type generValueType))
                    {
                        if (tIsGener == false ||
                          (generKeyType == genericKeyType && generValueType == genericValueType))
                        {
                            constructor = item;
                            if (!isFindEmptyCtor)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            return constructor != null;
        }

19 View Source File : SagaMaster.cs
License : MIT License
Project Creator : 2881099

SagaMaster<TDBKey> Then(Type sagaUnitType, object state)
        {
            if (sagaUnitType == null) throw new ArgumentNullException(nameof(sagaUnitType));
            var unitTypeBase = typeof(SagaUnit<>);
            if (state == null && sagaUnitType.BaseType.GetGenericTypeDefinition() == typeof(SagaUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(sagaUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(sagaUnitType) == false) throw new ArgumentException($"{sagaUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = sagaUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{sagaUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(sagaUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{sagaUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ISagaUnit;
            (unit as ISagaUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new SagaUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = SagaUnitStage.Commit,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = sagaUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : TccMaster.cs
License : MIT License
Project Creator : 2881099

TccMaster<TDBKey> Then(Type tccUnitType, object state)
        {
            if (tccUnitType == null) throw new ArgumentNullException(nameof(tccUnitType));
            var unitTypeBase = typeof(TccUnit<>);
            if (state == null && tccUnitType.BaseType.GetGenericTypeDefinition() == typeof(TccUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(tccUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(tccUnitType) == false) throw new ArgumentException($"{tccUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = tccUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{tccUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(tccUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{tccUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ITccUnit;
            (unit as ITccUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new TccUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = TccUnitStage.Try,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = tccUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static int GetConstructorCount(Type type)
            {
               return type.GetConstructors().Length;
            }

19 View Source File : ObjectFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public object CreateInstance(Type type)
        {
            if (type == typeof(IObjectFactory))
            {
                return this;
            }
            
            if (type == typeof(Instance))
            {
                return _instance;
            }

            if (TryGetImplementation(type, out Type implementationType))
            {
                return CreateInstance(implementationType);
            }

            if (type.GetConstructor(Type.EmptyTypes) is not null)
            {
                return Activator.CreateInstance(type);
            }

            ConstructorInfo info = type.GetConstructors()[0];
            ParameterInfo[] parameters = info.GetParameters();
            object[] parameterObjects = new object[parameters.Length];
            int i = 0;
            foreach (ParameterInfo parameter in info.GetParameters())
            {
                parameterObjects[i] = CreateInstance(parameter.ParameterType);
                i++;
            }

            return Activator.CreateInstance(type, parameterObjects);
        }

19 View Source File : SpParameterTest.cs
License : Apache License 2.0
Project Creator : agoda-com

[Test]
        public void CreateCacheKey_Types()
        {
            var safeTypes = new[]
            {
                typeof(int),
                typeof(string),
                typeof(long),
                typeof(double),
                typeof(char),
                typeof(bool),
                typeof(DateTime),
                typeof(Guid),
            };
            var intParam = new SpParameter("int", 55);
            var stringParam = new SpParameter("string", "foo");
            var longParam = new SpParameter("long", 55L);
            var doubleParam = new SpParameter("double", 3.14);
            var charParam = new SpParameter("char", '*');
            var boolParam = new SpParameter("bool", true);
            var dateTimeParam = new SpParameter("DateTime", new DateTime(2000, 1, 1));
            var guidParam = new SpParameter("Guid", new Guid("dddddddd-dddd-dddd-dddd-dddddddddddd"));

            var parameters = new[]
            {
                intParam,
                stringParam,
                longParam,
                doubleParam,
                charParam,
                boolParam,
                dateTimeParam,
                guidParam
            };
            var key = parameters.CreateCacheKey("sp_foo");

            replacedert.AreEqual(
                "db.v1.sp_foo:" +
                "@bool+True&" +
                "@char+*&" +
                "@DateTime+630822816000000000&" +
                "@double+3.14&" +
                "@Guid+dddddddd-dddd-dddd-dddd-dddddddddddd&" +
                "@int+55&" +
                "@long+55&" +
                "@string+foo&",
                key);

            var ctors = typeof(SpParameter).GetConstructors();
            foreach (var info in ctors)
            {
                replacedert.IsTrue(
                    safeTypes.Any(t => t == info.GetParameters()[1].ParameterType),
                    "All ctor types for SpParameter need to add " +
                    "instance to the list above and update the test.");
            }
            replacedert.AreEqual(safeTypes.Length, ctors.Length);
        }

19 View Source File : ServiceCollectionExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static object CreateStore(Func<IServiceProvider, Task<HttpClient>> getHttpClient, IServiceProvider provider, Type enreplacedyType)
        {
            var adminStoreType = typeof(AdminStore<>)
                        .MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();

            var loggerType = typeof(ILogger<>).MakeGenericType(adminStoreType);
            return adminStoreType.GetConstructors()[0]
                .Invoke(new object[] { getHttpClient.Invoke(provider), provider.GetRequiredService(loggerType) });
        }

19 View Source File : InstranceMaker.cs
License : MIT License
Project Creator : AiursoftWeb

private static object GenerateWithConstructor(Type type)
        {
            // Has default constructor.
            if (type.GetConstructors().Length == 1 &&
                !type.GetConstructors()[0].GetParameters().Any() &&
                !type.IsAbstract)
            {
                return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty);
            }
            else if (type.GetConstructors().Any(t => t.IsPublic) && !type.IsAbstract)
            {
                // Has a constructor, and constructor has some arguments.
                var constructor = type.GetConstructors()[0];
                var args = constructor.GetParameters();
                object[] parameters = new object[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    var requirement = args[i].ParameterType;
                    parameters[i] = Make(requirement);
                }
                return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty, true, BindingFlags.Default, null, parameters, null, null);
            }
            else if (type.IsAbstract)
            {
                return null;
            }
            else if (!type.GetConstructors().Any(t => t.IsPublic))
            {
                return null;
            }
            else
            {
                return replacedembly.Getreplacedembly(type)?.CreateInstance(type.FullName ?? string.Empty);
            }
        }

19 View Source File : DbContextOptionsSpecimenBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoDomainData]
        public void Ctors_ShouldReceiveInitializedParameters(GuardClausereplacedertion replacedertion)
        {
            var members = typeof(DbContextOptionsSpecimenBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : InMemoryOptionsBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoData]
        public void Ctors_ShouldReceiveInitializedParameters(Fixture fixture)
        {
            var replacedertion = new GuardClausereplacedertion(fixture);
            var members = typeof(InMemoryOptionsBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : InMemoryOptionsSpecimenBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoDomainData]
        public void Ctors_ShouldReceiveInitializedParameters(GuardClausereplacedertion replacedertion)
        {
            var members = typeof(InMemoryOptionsSpecimenBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : SqliteConnectionSpecimenBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoDomainData]
        public void Ctors_ShouldReceiveInitializedParameters(GuardClausereplacedertion replacedertion)
        {
            var members = typeof(SqliteConnectionSpecimenBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : SqliteOptionsBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoData]
        public void Ctors_ShouldInitializeProperties(ConstructorInitializedMemberreplacedertion replacedertion)
        {
            var members = typeof(SqliteOptionsBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : SqliteOptionsBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoData]
        public void Ctors_ShouldReceiveInitializedParameters(Fixture fixture, GuardClausereplacedertion replacedertion)
        {
            fixture.Inject(new SqliteConnection("Data Source=:memory:"));
            var members = typeof(SqliteOptionsBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : SqliteOptionsSpecimenBuilderTests.cs
License : MIT License
Project Creator : aivascu

[Theory]
        [AutoDomainData]
        public void Ctors_ShouldReceiveInitializedParameters(Fixture fixture)
        {
            var replacedertion = new GuardClausereplacedertion(fixture);
            var members = typeof(SqliteOptionsSpecimenBuilder).GetConstructors();

            replacedertion.Verify(members);
        }

19 View Source File : AutoFakeIt.cs
License : MIT License
Project Creator : akamud

public T Generate<T>() where T : clreplaced
        {
            var constructors = typeof(T).GetConstructors()
                .OrderByDescending(ctor => ctor.GetParameters().Length)
                .ToList();

            Exception? lastThrownException = null;
            foreach (var ctor in constructors)
            {
                try
                {
                    var candidateFakeObjects = GenerateCandidateFakeObjects(ctor);

                    var generatedObject = (T)ctor.Invoke(candidateFakeObjects.Values.ToArray());

                    InsertMissingFakedObjects(candidateFakeObjects);

                    return generatedObject;
                }
                catch (Exception ex)
                {
                    lastThrownException = ex;
                    // Keep looking for a suitable constructor
                }
            }

            throw new ArgumentException($"No suitable constructor found for type '{typeof(T)}'.", lastThrownException);
        }

19 View Source File : DefaultContractResolver.cs
License : MIT License
Project Creator : akaskela

private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member)
        {
            JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute<JsonExtensionDataAttribute>(member);
            if (extensionDataAttribute == null)
            {
                return;
            }

            Type t = ReflectionUtils.GetMemberUnderlyingType(member);

            Type dictionaryType;
            ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType);

            Type keyType = dictionaryType.GetGenericArguments()[0];
            Type valueType = dictionaryType.GetGenericArguments()[1];

            Type createdType;

            // change type to a clreplaced if it is the base interface so it can be instantiated if needed
            if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>)))
            {
                createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
            }
            else
            {
                createdType = t;
            }

            Func<object, object> getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(member);

            if (extensionDataAttribute.ReadData)
            {
                Action<object, object> setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false))
                 ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(member)
                 : null;
                Func<object> createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
                MethodInfo addMethod = t.GetMethod("Add", new[] { keyType, valueType });
                MethodCall<object, object> setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(addMethod);

                ExtensionDataSetter extensionDataSetter = (o, key, value) =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        if (setExtensionDataDictionary == null)
                        {
                            throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name));
                        }

                        dictionary = createExtensionDataDictionary();
                        setExtensionDataDictionary(o, dictionary);
                    }

                    setExtensionDataDictionaryValue(dictionary, key, value);
                };

                contract.ExtensionDataSetter = extensionDataSetter;
            }

            if (extensionDataAttribute.WriteData)
            {
                Type enumerableWrapper = typeof(EnumerableDictionaryWrapper<,>).MakeGenericType(keyType, valueType);
                ConstructorInfo constructors = enumerableWrapper.GetConstructors().First();
                ObjectConstructor<object> createEnumerableWrapper = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructors);

                ExtensionDataGetter extensionDataGetter = o =>
                {
                    object dictionary = getExtensionDataDictionary(o);
                    if (dictionary == null)
                    {
                        return null;
                    }

                    return (IEnumerable<KeyValuePair<object, object>>)createEnumerableWrapper(dictionary);
                };

                contract.ExtensionDataGetter = extensionDataGetter;
            }

            contract.ExtensionDataValueType = valueType;
        }

19 View Source File : OpenEdgeCompositeMethodCallTranslator.cs
License : Apache License 2.0
Project Creator : alexwiese

public static IEnumerable<Type> GetTranslatorMethods<TInteface>()
            => replacedembly
                .GetExecutingreplacedembly()
                .GetTypes().Where(t =>
                    t.GetInterfaces().Any(i => i == typeof(TInteface))
                    && t.GetConstructors().Any(c => c.GetParameters().Length == 0));

19 View Source File : DynamoDbContextMetadata.cs
License : MIT License
Project Creator : AllocZero

private DdbConverter CreateConverter(Type converterType)
        {
            var constructor = converterType.GetConstructors()[0];
            var constructorParams = constructor.GetParameters();

            if (constructorParams.Length == 0) 
                return (DdbConverter) Activator.CreateInstance(converterType)!;

            var parameters = new object[constructorParams.Length];
            for (var i = 0; i < constructorParams.Length; i++)
            {
                var parameter = constructorParams[i];

                if (parameter.ParameterType == typeof(DynamoDbContextMetadata))
                {
                    parameters[i] = this;
                }
                else
                {
                    if (!parameter.ParameterType.IsSubclreplacedOf(typeof(DdbConverter))) 
                        throw new DdbException("Can't create converter that contains non converter constructor parameters.");

                    parameters[i] = GetOrAddConverter(parameter.ParameterType.GenericTypeArguments[0], null);
                }
            }

            return (DdbConverter) Activator.CreateInstance(converterType, parameters)!;
        }

19 View Source File : ObjectInfo.cs
License : MIT License
Project Creator : amolines

public ConstructorInfo[] GetConstructors(Type type)
        {
            return type.GetConstructors();
        }

19 View Source File : ObjectInfo.cs
License : MIT License
Project Creator : amolines

public ConstructorInfo[] GetConstructors(Type type, Type[] genericTypes)
        {
            var genericType = type.MakeGenericType(genericTypes);
            return genericType.GetConstructors();
        }

19 View Source File : FeaturesTests.cs
License : MIT License
Project Creator : amis92

[Fact]
        public void Given_Constructor_then_ctor_is_generated()
        {
            var ctors = typeof(FeatureContainer.FeatureConstructor).GetConstructors();

            ctors.Should().ContainSingle(x => x.GetParameters().Length == 1, "generated ctor has 1 parameter");
        }

19 View Source File : IServiceContainer.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private static ConstructorInfo FindServiceProxyContructor(Type serviceProxyType, Type serviceInterfaceType)
        {
            //Go though the list of all constructors to find target
            foreach (ConstructorInfo constructor in serviceProxyType.GetConstructors())
            {
                //Get parameters
                ParameterInfo[] parameters = constructor.GetParameters();
                //We are looking for contructor with 1 parameter that has type of real object
                if (parameters.Length != 1)
                {
                    continue;
                }
                ParameterInfo firstParameter = parameters[0];
                //Check that first parameter is replacedignable from serviceInterfaceType
                if (!firstParameter.ParameterType.IsreplacedignableFrom(serviceInterfaceType))
                {
                    continue;
                }
                return constructor;
            }
            return null;
        }

19 View Source File : DatabaseOperation.cs
License : MIT License
Project Creator : ap0405140

public List<T> Query<T>(string sTsql, bool closeconnect = true)
        {
            DataTable dt;
            List<T> ls;
            T tt;
            object tt2;
            PropertyInfo[] props;
            FieldInfo fieldinfo;
            DataColumn[] dtcolumns;
            ColumnAttribute[] columnattributes;
            string targettype, columnname;
            int i;

            try
            {
                dt = Query(sTsql, closeconnect);
                dtcolumns = dt.Columns.Cast<DataColumn>().ToArray();
                ls = new List<T>();

                targettype = "";
                if (typeof(T).IsValueType 
                    || typeof(T).Name.ToLower().Contains("string"))
                {
                    targettype = "ValueType";
                }
                if (typeof(T).Name.StartsWith("ValueTuple"))
                {
                    targettype = "ValueTuple";
                }
                if (typeof(T).GetConstructors().Any(p => p.GetParameters().Length == 0))
                {
                    targettype = "Clreplaced";
                }

                foreach (DataRow dr in dt.Rows)
                {
                    switch (targettype)
                    {
                        case "ValueType":
                            tt = (dr[0] == DBNull.Value ? default(T) : (T)dr[0]);
                            ls.Add(tt);
                            break;
                        case "ValueTuple":
                            tt = Activator.CreateInstance<T>();
                            tt2 = tt;
                            for (i = 0; i <= dtcolumns.Length - 1; i++)
                            {
                                fieldinfo = tt2.GetType().GetField("Item" + (i + 1).ToString());
                                if (fieldinfo != null)
                                {
                                    fieldinfo.SetValue(tt2, (dr[i] == DBNull.Value ? null : dr[i].ToSpecifiedType(fieldinfo.FieldType)));
                                }
                            }
                            tt = (T)tt2;
                            ls.Add(tt);
                            break;
                        case "Clreplaced":
                            tt = (T)Activator.CreateInstance(typeof(T));
                            props = typeof(T).GetProperties();
                            foreach (PropertyInfo prop in props)
                            {
                                columnattributes = prop.GetCustomAttributes(typeof(ColumnAttribute), false).Cast<ColumnAttribute>().ToArray();
                                columnname = (columnattributes.Length > 0 && string.IsNullOrEmpty(columnattributes[0].Name) == false
                                                ?
                                                   columnattributes[0].Name
                                                :
                                                   prop.Name);
                                if (dtcolumns.Any(c => c.ColumnName == columnname))
                                {
                                    prop.SetValue(tt, (dr[columnname] == DBNull.Value ? null : dr[columnname]));
                                }
                            }
                            ls.Add(tt);
                            break;
                        default:
                            break;
                    }
                }

                return ls;
            }
            catch (Exception ex)
            {
                throw new Exception("Run SQL: \r\n" + sTsql
                                    + "\r\n\r\n" + "ExceptionSource: " + ex.Source
                                    + "\r\n\r\n" + "ExceptionMessage: " + ex.Message);
            }
            finally
            {
                //if (closeconnect == true)
                //{
                //    if (scn.State == ConnectionState.Open)
                //    {
                //        scn.Close();
                //    }

                //    scn.Dispose();
                //}
            }
        }

19 View Source File : MainResolver.cs
License : MIT License
Project Creator : areller

public void AddResolver(Type type, Type proxy)
        {
            var typeInfo = type.GetTypeInfo();
            var proxyTypeInfo = proxy.GetTypeInfo();

            if (typeInfo.GenericTypeParameters.Length != proxyTypeInfo.GenericTypeParameters.Length)
            {
                throw new Exception("Base type and proxy must have the same type parameters");
            }

            var paramsOrdinal = Enumerable.Range(0, proxyTypeInfo.GenericTypeParameters.Length)
                .Select(i => (i, proxyTypeInfo.GenericTypeParameters[i]))
                .ToDictionary(p => p.Item2.Name, p => p.i);

            var dataTypeAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILDataType) as RedILDataType;
            var dataType = DataValueType.Unknown;
            if (!(dataTypeAttr is null))
            {
                dataType = dataTypeAttr.Type;
            }

            RedILValueResolver valueResolver = null;
            var valueResolveAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;
            if (!(valueResolveAttr is null))
            {
                valueResolver = valueResolveAttr.CreateValueResolver();
            }

            var constructors = new List<Constructor>();
            var instanceMethods = new List<Method>();
            var instanceMembers = new List<Member>();
            var staticMethods = new List<Method>();
            var staticMembers = new List<Member>();

            foreach (var ctor in proxy.GetConstructors())
            {
                var resolveAttr = ctor.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = ctor.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateObjectResolver();
                constructors.Add(new Constructor()
                {
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var method in proxy.GetMethods())
            {
                var resolveAttr = method.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = method.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateMethodResolver();
                (method.IsStatic ? staticMethods : instanceMethods).Add(new Method()
                {
                    Name = method.Name,
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var member in proxy.GetProperties())
            {
                var resolveAttr = member.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var resolver = resolveAttr.CreateMemberResolver();
                (member.GetAccessors().First().IsStatic ? staticMembers : instanceMembers).Add(new Member()
                {
                    Name = member.Name,
                    Resolver = resolver
                });
            }

            if (proxy.IsEnum)
            {
                foreach (var enumName in proxy.GetEnumNames())
                {
                    var field = proxy.GetField(enumName);
                    var resolveAttr = field?.GetCustomAttributes()
                        ?.FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                    if (resolveAttr is null)
                    {
                        continue;
                    }

                    var resolver = resolveAttr.CreateMemberResolver();
                    staticMembers.Add(new Member()
                    {
                        Name = enumName,
                        Resolver = resolver
                    });
                }
            }

            _typeDefs.Add(type.FullName, new TypeDefinition()
            {
                DataType = dataType,
                ValueResolver = valueResolver,
                ParametersOrdinal = paramsOrdinal,
                Constructors = constructors.GroupBy(c => c.Signature.Length).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMethods = instanceMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMembers = instanceMembers.ToDictionary(m => m.Name, m => m),
                StaticMethods = staticMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                StaticMembers = staticMembers.ToDictionary(m => m.Name, m => m)
            });
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private static Tuple<Type, Delegate, object[]> ToConstructorMiddlewareFactory(object middlewareObject, object[] args, ref Delegate middlewareDelegate)
        {
            var middlewareType = middlewareObject as Type;
            ConstructorInfo[] constructors = middlewareType.GetConstructors();
            foreach (var constructor in constructors)
            {
                ParameterInfo[] parameters = constructor.GetParameters();
                Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
                if (parameterTypes.Length != args.Length + 1)
                {
                    continue;
                }
                if (!parameterTypes
                    .Skip(1)
                    .Zip(args, TestArgForParameter)
                    .All(x => x))
                {
                    continue;
                }

                ParameterExpression[] parameterExpressions = parameters.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();
                NewExpression callConstructor = Expression.New(constructor, parameterExpressions);
                middlewareDelegate = Expression.Lambda(callConstructor, parameterExpressions).Compile();
                return Tuple.Create(parameters[0].ParameterType, middlewareDelegate, args);
            }

            throw new MissingMethodException(string.Format(CultureInfo.CurrentCulture,
                Resources.Exception_NoConstructorFound, middlewareType.FullName, args.Length + 1));
        }

19 View Source File : ActivatorUtilities.cs
License : Apache License 2.0
Project Creator : aspnet

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);
        }

19 View Source File : RequestServicesFeatureFactory.cs
License : MIT License
Project Creator : autofac

private static Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature> GenerateLambda()
        {
            var constructor = typeof(RequestServicesFeature).GetConstructors().OrderByDescending(ci => ci.GetParameters().Length).First();
            var parameterCount = constructor.GetParameters().Length;
            var contextParameter = Expression.Parameter(typeof(HttpContext), "context");
            var factoryParameter = Expression.Parameter(typeof(IServiceScopeFactory), "factory");
            switch (parameterCount)
            {
                case 1:
                    // ASP.NET Core through 2.1 has RequestServicesFeature ctor only with scope factory.
                    var subExpression = Expression.Lambda<Func<IServiceScopeFactory, IServiceProvidersFeature>>(
                        Expression.Convert(
                            Expression.New(
                                constructor,
                                factoryParameter),
                            typeof(IServiceProvidersFeature)),
                        factoryParameter)
                        .Compile();
                    return (ctx, factory) => subExpression(factory);
                case 2:
                    // ASP.NET Core 2.1 changed RequestServicesFeature ctor to take context and scope factory.
                    return Expression.Lambda<Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature>>(
                        Expression.Convert(
                            Expression.New(
                                constructor,
                                contextParameter,
                                factoryParameter),
                            typeof(IServiceProvidersFeature)),
                        contextParameter,
                        factoryParameter)
                        .Compile();
                default:
                    throw new NotSupportedException(Resources.NoSupportedRequestServicesConstructorFound);
            }
        }

19 View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper

protected override Expression VisitNew(NewExpression node)
        {
            if (this.TypeMappings.TryGetValue(node.Type, out Type newType))
            {
                return Expression.New(newType);
            }
            else if (node.Arguments.Count > 0 && IsAnonymousType(node.Type))
            {
                ParameterInfo[] parameters = node.Type.GetConstructors()[0].GetParameters();
                Dictionary<string, Expression> bindingExpressions = new Dictionary<string, Expression>();

                for (int i = 0; i < parameters.Length; i++)
                    bindingExpressions.Add(parameters[i].Name, this.Visit(node.Arguments[i]));

                return GetAnonymousTypeMemberInitExpression(bindingExpressions, node.Type);
            }

            return base.VisitNew(node);
        }

19 View Source File : GrpcAgentTestBase.cs
License : MIT License
Project Creator : Avanade

public TAgent CreateAgent<TAgent>(IWebApiAgentArgs? args = null) where TAgent : GrpcAgentBase
        {
            var agent = AgentTesterBase.LocalServiceProvider.GetService<TAgent>();
            if (agent != null)
                return agent;

            var ctors = typeof(TAgent).GetConstructors();
            if (ctors.Length != 1)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the constructor could not be determined.");

            var pis = ctors[0].GetParameters();
            if (pis.Length != 2)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the constructor must have two parameters.");

            var pi = pis[0];
            if (pi.ParameterType != typeof(IWebApiAgentArgs) && !pi.ParameterType.GetInterfaces().Contains(typeof(IWebApiAgentArgs)))
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the first constructor parameter must implement IWebApiAgentArgs.");

            var pi2 = pis[1];
            if (pi2.ParameterType != typeof(AutoMapper.IMapper))
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the second constructor parameter must be of Type AutoMapper.IMapper.");

            var obj = Activator.CreateInstance(typeof(TAgent), args ?? CreateAgentArgs(pi.ParameterType), AgentTesterBase.LocalServiceProvider.GetService<AutoMapper.IMapper>()
                ?? throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the LocalServiceProvider is unable to construct the required AutoMapper.IMapper parameter instance."));

            if (obj == null)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created.");

            return (TAgent)obj;
        }

19 View Source File : AgentTestBase.cs
License : MIT License
Project Creator : Avanade

public TAgent CreateAgent<TAgent>(IWebApiAgentArgs? args = null) where TAgent : WebApiAgentBase
        {
            var agent = AgentTesterBase.LocalServiceProvider.GetService<TAgent>();
            if (agent != null)
                return agent;

            var ctors = typeof(TAgent).GetConstructors();
            if (ctors.Length != 1)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the constructor could not be determined.");

            var pis = ctors[0].GetParameters();
            if (pis.Length != 1)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the constructor must only have a single parameter.");

            var pi = pis[0];
            if (pi.ParameterType != typeof(IWebApiAgentArgs) && !pi.ParameterType.GetInterfaces().Contains(typeof(IWebApiAgentArgs)))
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created; the constructor parameter must implement IWebApiAgentArgs.");

            var obj = Activator.CreateInstance(typeof(TAgent), args ?? CreateAgentArgs(pi.ParameterType));
            if (obj == null)
                throw new InvalidOperationException($"An instance of {typeof(TAgent).Name} was unable to be created.");

            return (TAgent)obj;
        }

19 View Source File : FactoryUtils.cs
License : MIT License
Project Creator : azist

public static T MakeUsingCtor<T>(IConfigSectionNode node, string typePattern = null)
    {
      string tpn = CoreConsts.UNKNOWN;
      try
      {
        if (node==null || !node.Exists)
          throw new ConfigException(StringConsts.ARGUMENT_ERROR+"FactoryUtils.Make(node==null|empty)");

        tpn = node.AttrByName(CONFIG_TYPE_ATTR).Value;

        if (tpn.IsNullOrWhiteSpace())
          tpn = typeof(T).replacedemblyQualifiedName;
        else
          if (typePattern.IsNotNullOrWhiteSpace())
            tpn = typePattern.Replace("*", tpn);

        var tp = Type.GetType(tpn, true);

        var args = new List<object>();
        for(var i=0; true; i++)
        {
          var attr = node.AttrByName("arg{0}".Args(i));
          if (!attr.Exists) break;
          args.Add(attr.Value);
        }

        var cinfo = tp.GetConstructors().FirstOrDefault(ci => ci.GetParameters().Length == args.Count);
        if (cinfo==null) throw new AzosException(".ctor arg count mismatch");

        //dynamically re-cast argument types
        for(var i=0; i<args.Count; i++)
          args[i] = args[i].ToString().AsType(cinfo.GetParameters()[i].ParameterType);

        try
        {
          return (T)Activator.CreateInstance(tp, args.ToArray());
        }
        catch(TargetInvocationException tie)
        {
          throw tie.InnerException;
        }
      }
      catch(Exception error)
      {
        throw new ConfigException(StringConsts.CONFIGURATION_MAKE_USING_CTOR_ERROR.Args(tpn, error.ToMessageWithType()), error);
      }
    }

19 View Source File : RDBMSCompiler.cs
License : MIT License
Project Creator : azist

protected virtual RDBMSDomain CreateDomain(string sourcePath, string name, IConfigNode node)
            {
               try
               {
                string argsLine = null;
                var iop = name.LastIndexOf('(');
                var icp = name.LastIndexOf(')');
                if (iop>0 && icp>iop)
                {
                  argsLine = name.Substring(iop+1, icp-iop-1);
                  name = name.Substring(0, iop);
                }

                Type dtype = Type.GetType(name, false, true);
                if (dtype==null)
                {
                    var paths = DomainSearchPaths.Split('|', ';');
                    foreach(var path in paths)
                    {
                        var fullName = path.Replace(".*", "." + name);
                        dtype = Type.GetType(fullName, false, true);
                        if (dtype!=null) break;
                    }
                }

                if (dtype==null)
                {
                      m_CompileErrors.Add(new SchemaCompilationException(sourcePath, "Domain type not found in any paths: " + name));
                      return null;
                }

                object[] args = null;
                var ctor = dtype.GetConstructor(Type.EmptyTypes);

                if (argsLine!=null)
                {
                    var argsStrings = argsLine.Split(',');
                    ctor = dtype.GetConstructors().Where(ci => ci.GetParameters().Length==argsStrings.Length).FirstOrDefault();
                    if (ctor==null)
                    {
                      m_CompileErrors.Add(new SchemaCompilationException(sourcePath, "Domain .ctor '{0}' argument mismatch '{1}'".Args(dtype.FullName, argsLine)));
                      return null;
                    }

                    args = new object[ctor.GetParameters().Length];
                    var i = 0;
                    foreach(var pi in ctor.GetParameters())
                    {
                        args[i] = argsStrings[i].Trim().AsType(pi.ParameterType);
                        i++;
                    }
                }

                var result = Activator.CreateInstance(dtype, args) as RDBMSDomain;
                if (node is IConfigSectionNode)
                    result.Configure((IConfigSectionNode)node);
                return result;
               }
               catch(Exception error)
               {
                 m_CompileErrors.Add(new SchemaCompilationException(sourcePath, "Domain '{0}' creation error: {1} ".Args(name, error.ToMessageWithType())));
                 return null;
               }
            }

19 View Source File : Comment.cs
License : MIT License
Project Creator : Azure-Functions

public static bool TryCreateFromForm(NameValueCollection form, out Comment comment, out List<string> errors)
        {
            var constructor = typeof(Comment).GetConstructors()[0];
            var values = constructor.GetParameters()
                .ToDictionary(
                    p => p.Name,
                    p => ConvertParameter(form[p.Name], p.ParameterType) ?? (p.HasDefaultValue ? p.DefaultValue : new MissingRequiredValue())
                );

            errors = values.Where(p => p.Value is MissingRequiredValue).Select(p => $"Form value missing for {p.Key}").ToList();
            if (values["email"] is string s && !validEmail.IsMatch(s))
                errors.Add("email not in correct format");

            comment = errors.Any() ? null : (Comment)constructor.Invoke(values.Values.ToArray());
            var isFormValid = !errors.Any();
            var config = PostCommentToPullRequestFunction.config;

            if (isFormValid && !string.IsNullOrEmpty(config.SentimentreplacedysisSubscriptionKey))
            {
                var textreplacedysis = new Sentimentreplacedysis(config.SentimentreplacedysisSubscriptionKey,
                    config.SentimentreplacedysisRegion,
                    config.SentimentreplacedysisLang);
                comment.score = textreplacedysis.replacedyze(comment.message);
            }
            else
            {
                comment.score = "Not configured";
            }

            return isFormValid;
        }

19 View Source File : PluginSettingsUIBuilder.cs
License : MIT License
Project Creator : b-editor

public static object GetValue(StackPanel stack, Type type)
        {
            var constructor = type.GetConstructors().First();
            var paramerters = constructor.GetParameters();
            var args = new object[paramerters.Length];

            for (var i = 0; i < paramerters.Length; i++)
            {
                var param = paramerters[i];
                var item = Find(param.ParameterType);

                args[i] = item.getValue((Control)stack.Children[i], param.ParameterType);
            }

            return Activator.CreateInstance(type, BindingFlags.CreateInstance, null, args, null)!;
        }

19 View Source File : SettingRecord.cs
License : MIT License
Project Creator : b-editor

public record SettingRecord()
    {
        /// <summary>
        /// Saves this configuration to the specified file.
        /// </summary>
        /// <param name="filename">The file to save.</param>
        /// <returns>Returns <see langword="true"/> if the save was successful, <see langword="false"/> otherwise.</returns>
        public bool Save(string filename)
        {
            try
            {
                using var stream = new FileStream(filename, FileMode.Create);
                using var writer = new Utf8JsonWriter(stream, Serialize._options);

                writer.WriteStartObject();

                foreach (var (param, prop) in GetSerializable(GetType()))
                {
                    var value = prop.GetValue(this);
                    if (value is null) continue;
                    WriteSerializable(writer, param.Name!, value);
                }

                writer.WriteEndObject();
                writer.Flush();
                return true;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to save {0}.", GetType().Name);
                return false;
            }
        }

        /// <summary>
        /// Saves this configuration to the specified file.
        /// </summary>
        /// <param name="filename">The file to save.</param>
        /// <returns>Returns <see langword="true"/> if the save was successful, <see langword="false"/> otherwise.</returns>
        public async ValueTask<bool> SaveAsync(string filename)
        {
            try
            {
                await using var stream = new FileStream(filename, FileMode.Create);
                await using var writer = new Utf8JsonWriter(stream, Serialize._options);

                writer.WriteStartObject();

                foreach (var (param, prop) in GetSerializable(GetType()))
                {
                    var value = prop.GetValue(this);
                    if (value is null) continue;
                    WriteSerializable(writer, param.Name!, value);
                }

                writer.WriteEndObject();
                await writer.FlushAsync();
                return true;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to save {0}.", GetType().Name);
                return false;
            }
        }

        /// <summary>
        /// Loads the settings from a file.
        /// </summary>
        /// <typeparam name="T">Type of the object to be loaded.</typeparam>
        /// <param name="filename">The name of the file to load.</param>
        /// <returns>Returns the restored object on success, <see langword="null"/> otherwise.</returns>
        public static T? LoadFrom<T>(string filename)
            where T : SettingRecord
        {
            if (!File.Exists(filename)) return default;
            try
            {
                using var stream = new FileStream(filename, FileMode.Open);

                using var doc = JsonDoreplacedent.Parse(stream);
                var type = typeof(T);
                var args = new List<object>();

                foreach (var (param, prop) in GetSerializable(type))
                {
                    if (doc.RootElement.TryGetProperty(param.Name!, out var json))
                    {
                        var value = ReadSerializable(json, param.ParameterType);
                        args.Add(value);
                    }
                    else
                    {
                        args.Add(GetDefault(type));
                    }
                }

                return (T)Activator.CreateInstance(type, BindingFlags.CreateInstance, null, args.ToArray(), null)!;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to load {0}.", filename);
                return default;
            }
        }

        /// <summary>
        /// Loads the settings from a file.
        /// </summary>
        /// <typeparam name="T">Type of the object to be loaded.</typeparam>
        /// <param name="filename">The name of the file to load.</param>
        /// <returns>Returns the restored object on success, <see langword="null"/> otherwise.</returns>
        public static async ValueTask<T?> LoadFromAsync<T>(string filename)
            where T : SettingRecord
        {
            if (!File.Exists(filename)) return default;
            try
            {
                await using var stream = new FileStream(filename, FileMode.Open);

                using var doc = await JsonDoreplacedent.ParseAsync(stream);
                var type = typeof(T);
                var args = new List<object>();

                foreach (var (param, prop) in GetSerializable(type))
                {
                    if (doc.RootElement.TryGetProperty(param.Name!, out var json))
                    {
                        var value = ReadSerializable(json, param.ParameterType);
                        args.Add(value);
                    }
                    else
                    {
                        args.Add(GetDefault(type));
                    }
                }

                return (T)Activator.CreateInstance(type, BindingFlags.CreateInstance, null, args.ToArray(), null)!;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to load {0}.", filename);
                return default;
            }
        }

        private static IEnumerable<(ParameterInfo Parameter, PropertyInfo Property)> GetSerializable(Type type)
        {
            var constructor = type.GetConstructors()[0];
            foreach (var param in constructor.GetParameters())
            {
                var name = param.Name;

                if (name is not null && type.GetProperty(name) is var prop && prop is not null && IsSerializable(prop.PropertyType))
                {
                    yield return (param, prop);
                }
            }

19 View Source File : JITExtensions.cs
License : MIT License
Project Creator : badamczewski

public static DecompiledMethod[] ToAsm(this Type typeInfo, bool @private = false)
        {
            List<DecompiledMethod> methods = new List<DecompiledMethod>();

            foreach (var constructorInfo in typeInfo.GetConstructors())
            {
                RuntimeHelpers.PrepareMethod(constructorInfo.MethodHandle);
            }

            var flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
            if (@private)
            {
                flags |= BindingFlags.NonPublic;
            }

            foreach (var methodInfo in typeInfo.GetMethods(flags))
            {
                if (methodInfo.DeclaringType != typeof(System.Object))
                {
                    var decompiledMethod = ToAsm(methodInfo);
                    methods.Add(decompiledMethod);
                }
            }

            return methods.ToArray();
        }

19 View Source File : Activation.cs
License : GNU General Public License v3.0
Project Creator : BardMusicPlayer

public static IEnumerable<ConstructorInfo> GetAllConstructors(this Type t) => t.GetConstructors().Concat(t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance));

19 View Source File : ModelBuilderExtensions.cs
License : Apache License 2.0
Project Creator : bcgov

public static ModelBuilder ApplyAllConfigurations(this ModelBuilder modelBuilder, replacedembly replacedembly, PimsContext context = null)
        {
            if (replacedembly == null) throw new ArgumentNullException(nameof(replacedembly));

            // Find all the configuration clreplacedes.
            var type = typeof(IEnreplacedyTypeConfiguration<>);
            var configurations = replacedembly.GetTypes().Where(t => t.IsClreplaced && t.GetInterfaces().Any(i => i.Name.Equals(type.Name)));

            // Fetch the ApplyConfiguration method so that it can be called on each configuration.
            var method = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(m => m.Name.Equals(nameof(ModelBuilder.ApplyConfiguration)) && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == type).First();
            foreach (var config in configurations)
            {
                if (!config.ContainsGenericParameters)
                {
                    var includeContext = config.GetConstructors().Any(c => c.GetParameters().Any(p => p.ParameterType == typeof(PimsContext)));
                    var enreplacedyConfig = includeContext ? Activator.CreateInstance(config, context) : Activator.CreateInstance(config);
                    var enreplacedyType = config.GetInterfaces().FirstOrDefault().GetGenericArguments()[0];
                    var applyConfigurationMethod = method.MakeGenericMethod(enreplacedyType);
                    applyConfigurationMethod.Invoke(modelBuilder, new[] { enreplacedyConfig });
                }
            }

            return modelBuilder;
        }

19 View Source File : ResolvingFactoriesExtensions.cs
License : MIT License
Project Creator : bcssov

public static void AllowResolvingLazyFactories(this Container container)
        {
            container.ResolveUnregisteredType += (sender, e) =>
            {
                if (e.UnregisteredServiceType.IsGenericType &&
                    e.UnregisteredServiceType.GetGenericTypeDefinition() == typeof(Lazy<>))
                {
                    var serviceType = e.UnregisteredServiceType.GetGenericArguments()[0];

                    var registration = container.GetRegistration(serviceType, true);

                    var funcType = typeof(Func<>).MakeGenericType(serviceType);
                    var lazyType = typeof(Lazy<>).MakeGenericType(serviceType);

                    var factoryDelegate = Expression.Lambda(funcType, registration.BuildExpression()).Compile();

                    var lazyConstructor = (
                        from ctor in lazyType.GetConstructors()
                        where ctor.GetParameters().Length == 1
                        where ctor.GetParameters()[0].ParameterType == funcType
                        select ctor)
                        .Single();

                    var expression = Expression.New(lazyConstructor, Expression.Constant(factoryDelegate));

                    var lazyRegistration = registration.Lifestyle.CreateRegistration(
                        serviceType: lazyType,
                        instanceCreator: Expression.Lambda<Func<object>>(expression).Compile(),
                        container: container);

                    e.Register(lazyRegistration);
                }
            };
        }

19 View Source File : AutoRewriter.cs
License : MIT License
Project Creator : benjamin-hodgson

private static ConstructorInfo GetBestConstructor(Type nodeType)
            => nodeType
                .GetConstructors()
                .OrderByDescending(c => c.GetParameters().Length)
                .FirstOrDefault();

19 View Source File : ConstructorProfiler.cs
License : GNU Lesser General Public License v3.0
Project Creator : BepInEx

private void InstallHooks()
        {
            var replacedes = AppDomain.CurrentDomain.Getreplacedemblies().Where(x =>
                {
                    if (new[] { "ConstructorProfiler", "mscorlib" }.Any(y => x.FullName.Contains(y))) return false;
                    //try{if (x.Location.Contains("BepInEx")) return true;}
                    //catch{}


                    return true; //false; //replacedFilter.Contains(x.FullName.Split(',')[0]);
                })
                .ToList(); //.Where(replaced => replacedFilter.Contains(replaced.FullName.Split(',')[0])).ToList();
            var types = replacedes.SelectMany(replaced =>
                {
                    try
                    {
                        return replaced.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        return ex.Types.Where(x => x != null);
                    }
                }).Where(x => x.IsClreplaced && !x.IsGenericType)
                //.Where(x =>
                //{
                //    if (x.replacedembly.FullName.Contains("mscorlib"))
                //    {
                //        return  //(x.Namespace == null || x.Namespace == "System") && 
                //                !x.Name.Contains("Exception") && 
                //                !x.Name.Contains("Object") && 
                //                !x.Name.Contains("String") && 
                //                x.Namespace?.Contains("Diagnostics") != true;
                //    }
                //
                //    return true;
                //})
                .ToList();
            //var constructors = types.SelectMany(type => type.GetConstructors()).Where(x => !x.FullDescription().Contains("<") || !x.FullDescription().Contains(">")).ToList();
            var constructors = types.SelectMany(type => type.GetConstructors()).ToList();

            //int index = 0;
            foreach (var constructor in constructors)
            {
                //if(index > 1000)
                //    return;
                //index++;

                try
                {
                    //Logger.LogInfo($"Patching {constructor.FullDescription()}");
                    harmony.Patch(constructor, new HarmonyMethod(AddCallMethodInfo));
                }
                catch (Exception)
                {
                    Logger.LogWarning($"Exception patching {constructor.FullDescription()}");
                }
            }
        }

19 View Source File : ResolverService.cs
License : MIT License
Project Creator : bilal-fazlani

internal object? ResolveCommandClreplaced(Type clreplacedType, CommandContext commandContext)
        {
            // Default uses Resolve so the container can throw an exception if the clreplaced isn't registered.
            // if null is returned, then the container gives consent for other the clreplaced to
            // be created by this framework. 
            if (ConditionalTryResolve(clreplacedType, out var item, CommandClreplacedResolveStrategy))
            {
                return item;
            }

            var parameterResolversByType = commandContext.AppConfig.ParameterResolversByType;

            // NOTE: it's possible, that a clreplaced could appear more than once in the hierarchy.
            //       because this seems VERY unlikely to be needed, skip this case until
            //       proven it is needed to avoid additional state and complexity to
            //       reuse the instance.  the instance should be reused to map to expectation
            //       for DI that one instance is created per scope.
            var ctor = clreplacedType.GetConstructors()
                .Select(c => new { c, p = c.GetParameters() })
                .Where(cp => cp.p.Length == 0 || cp.p.All(p => parameterResolversByType.ContainsKey(p.ParameterType)))
                .OrderByDescending(cp => cp.p.Length)
                .FirstOrDefault();

            if (ctor == null)
            {
                throw new InvalidConfigurationException(
                    $"No viable constructors found for {clreplacedType}. " +
                    $"Constructor can only contain parameters of type: {parameterResolversByType.Keys.ToOrderedCsv()}");
            }

            var parameters = ctor.p
                .Select(p => parameterResolversByType[p.ParameterType](commandContext))
                .ToArray();

            item = ctor.c.Invoke(parameters);

            // only dispose instances created by this middleware, not by a container
            RegisterDisposable(commandContext, item);
            return item;
        }

19 View Source File : MethodWarpsCache.cs
License : MIT License
Project Creator : blueberryzzz

public LuaCSFunction GetConstructorWrap(Type type)
        {
            //UnityEngine.Debug.LogWarning("GetConstructor:" + type);
            if (!constructorCache.ContainsKey(type))
            {
                var constructors = type.GetConstructors();
                if (type.IsAbstract() || constructors == null || constructors.Length == 0)
                {
                    if (type.IsValueType())
                    {
                        constructorCache[type] = (L) =>
                        {
                            translator.PushAny(L, Activator.CreateInstance(type));
                            return 1;
                        };
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    LuaCSFunction ctor = _GenMethodWrap(type, ".ctor", constructors, true).Call;
                    
                    if (type.IsValueType())
                    {
                        bool hasZeroParamsCtor = false;
                        for (int i = 0; i < constructors.Length; i++)
                        {
                            if (constructors[i].GetParameters().Length == 0)
                            {
                                hasZeroParamsCtor = true;
                                break;
                            }
                        }
                        if (hasZeroParamsCtor)
                        {
                            constructorCache[type] = ctor;
                        }
                        else
                        {
                            constructorCache[type] = (L) =>
                            {
                                if (LuaAPI.lua_gettop(L) == 1)
                                {
                                    translator.PushAny(L, Activator.CreateInstance(type));
                                    return 1;
                                }
                                else
                                {
                                    return ctor(L);
                                }
                            };
                        }
                    }
                    else
                    {
                        constructorCache[type] = ctor;
                    }
                }
            }
            return constructorCache[type];
        }

19 View Source File : CodeCompletionListBox.cs
License : MIT License
Project Creator : BoltBait

internal void PopulateConstructors(Type type)
        {
            Clear();
            this.intelliBoxContents = IntelliBoxContents.Constructors;

            if (type.IsValueType)
            {
                unFilteredItems.Add(new IntelliBoxItem($"{type.Name}()", string.Empty, $"{type.Name}()", IntelliType.Constructor));
            }

            foreach (ConstructorInfo constructor in type.GetConstructors())
            {
                string toolTip = $"{type.Name}({constructor.Params()})";
                unFilteredItems.Add(new IntelliBoxItem(toolTip, string.Empty, toolTip + "\nConstructor", IntelliType.Constructor));
            }

            this.Items.AddRange(unFilteredItems.ToArray());
            if (unFilteredItems.Count > 0)
            {
                this.SelectedIndex = 0;
            }
        }

See More Examples