Csharp/C Sharp by API/System.Reflection/ConstructorInfo
ConstructorInfo.GetParameters()
using System;
using System.Reflection;
class MyClass {
public MyClass(int i) {
Console.WriteLine("Constructing MyClass(int). ");
}
public MyClass(int i, int j) {
Console.WriteLine("Constructing MyClass(int, int). ");
}
public int sum() {
return 0;
}
public bool isBetween(int i) {
return false;
}
public void set(int a, int b) {
Console.Write("Inside set(int, int). ");
}
public void set(double a, double b) {
Console.Write("Inside set(double, double). ");
}
public void show() {
Console.WriteLine("Values");
}
}
class MainClass {
public static void Main() {
Type t = typeof(MyClass);
// Get constructor info.
ConstructorInfo[] ci = t.GetConstructors();
Console.WriteLine("Available constructors: ");
foreach(ConstructorInfo c in ci) {
// Display return type and name.
Console.Write(" " + t.Name + "(");
// Display parameters.
ParameterInfo[] pi = c.GetParameters();
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name + " " + pi[i].Name);
if(i+1 < pi.Length)
Console.Write(", ");
}
Console.WriteLine(")");
}
Console.WriteLine();
}
}
ConstructorInfo.Invoke
using System;
using System.Text;
using System.Reflection;
class MainClass
{
public static void Main ()
{
Type type = typeof(StringBuilder);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo cInfo = type.GetConstructor(argTypes);
object[] argVals = new object[] { "Some string", 30 };
// Create the object and cast it to StringBuilder.
StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals);
Console.WriteLine(sb);
}
}