SoFunction
Updated on 2025-03-06

Interpretation of GetConstructor method for C# reflection programming

C# GetConstructor() method

The GetConstructor() method in the Type class is used to obtain the specific constructor of the class represented by the current Type.

There are 4 reloads

GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])
GetConstructor(BindingFlags, Type[])
GetConstructor(Type[])

Take GetConstructor(Type[]) as an example

Type[] in the formal parameters represents the required constructor parameters, order and type array of Type objects. If it is an empty parameter constructor, you can set Type[] to an empty array.

The return type is the ConstructorInfo type. An object representing a common instance constructor, if not, null.

Example code:

using System;
using ;

public class MyClass1
{
    public MyClass1() { }
    public MyClass1(int i) { }

    public static void Main()
    {
        try
        {
            Type myType = typeof(MyClass1);
            Type[] types = new Type[1];
            types[0] = typeof(int);
            // Get the constructor that takes an integer as a parameter.
            ConstructorInfo constructorInfoObj = (types);
            if (constructorInfoObj != null)
            {
                ("The constructor of MyClass1 that takes an " +
                    "integer as a parameter is: ");
                (());
            }
            else
            {
                ("The constructor of MyClass1 that takes an integer " +
                    "as a parameter is not available.");
            }
        }
        catch (Exception e)
        {
            ("Exception caught.");
            ("Source: " + );
            ("Message: " + );
        }
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.