Csharp/C Sharp/Reflection/ConstructorInfo
Call GetConstructor to get the constructor
<source lang="csharp"> using System; using System.Text; using System.Reflection; class MainClass {
public static StringBuilder CreateStringBuilder() { 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 }; StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals); return sb; }
}
</source>
Get parameter information by using ConstructorInfo and ParameterInfo
<source lang="csharp"> using System; using System.Collections; using System.Reflection; public class MainClass{
public static void Main() { Assembly LoadedAsm = Assembly.LoadFrom("yourName"); Console.WriteLine(LoadedAsm.FullName); Type[] LoadedTypes = LoadedAsm.GetTypes(); if (LoadedTypes.Length == 0) { Console.WriteLine("\tNo Types!"); } else { Console.WriteLine("\tFound Types:"); foreach (Type t in LoadedTypes) { if (t.IsPublic && !t.IsEnum && !t.IsValueType) { Console.WriteLine("Type: {0}", t.FullName); PrintConstructorInfo(t); } } } } private static void PrintConstructorInfo(Type t) { ConstructorInfo[] ctors = t.GetConstructors(); foreach (ConstructorInfo c in ctors) { ParameterInfo[] pList = c.GetParameters(); if (pList.Length == 0) { if (c.IsStatic) Console.WriteLine("\tFound static Constructor."); else Console.WriteLine("\tFound default consructor."); } else { Console.WriteLine("\tConstructor:"); foreach (ParameterInfo p in pList) { Console.WriteLine("\t\t{0} {1}", p.ParameterType.FullName,p.Name); } } } }
}
</source>
Invoke in Constructor through ConstructorInfo
<source lang="csharp">
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 }; StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals); Console.WriteLine(sb.ToString()); }
}
</source>