public class MyClass { public MyClass(int id, string name) { this.Id = id; this.Name = name; } public int Id { get; set; } public string Name { get; set; } } ConstructorInfo constructor = typeof(MyClass).GetConstructor(new[] { typeof(int), typeof(string) }); ParameterInfo[] parameters = constructor.GetParameters(); foreach (ParameterInfo parameter in parameters) { Console.WriteLine(parameter.Name + " " + parameter.ParameterType); }
public void InvokeConstructor(object instance, object[] args) { Type type = instance.GetType(); ConstructorInfo constructor = type.GetConstructor(args.Select(a => a.GetType()).ToArray()); if (constructor != null) { object newObject = constructor.Invoke(args); return newObject; } else { return null; } }This example defines a method that takes an object instance and an array of arguments as parameters. The code uses reflection to find a matching constructor for the instance and arguments, and then invokes the constructor to create a new object. The method returns the new object or null if no constructor can be found. Package library: System.Reflection