Get Constructor - CSharp System.Reflection

CSharp examples for System.Reflection:ConstructorInfo

Description

Get Constructor

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;//from w w  w. jav a 2  s. c o  m
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static ConstructorInfo GetConstructor(this Type type, BindingFlags flags, Type[] parameterTypes)
        {
            var info = type.GetTypeInfo();
            var cons = info.GetConstructors(flags);
            foreach (var con in cons)
            {
                var ps = con.GetParameters();
                if (ps.Length != parameterTypes.Length) continue;

                var allMatch = true;

                for (var i = 0; i < ps.Length; i++)
                {
                    var p = ps[i].ParameterType;
                    var pt = parameterTypes[i];
                    if (pt != p)
                    {
                        allMatch = false;
                    }
                }

                if (allMatch) return con;
            }

            return null;
        }
}

Related Tutorials