Reflection Call Constructor

CSharp · Console

/Program.cs

using System;
using System.Reflection;
					
public class Program
{
	public static void Main()
	{
		Type type = typeof(MyClass);
		// 使用 Activator.CreateInstance
		Activator.CreateInstance(type, new object[] { 10 });
		Activator.CreateInstance(type, new object[] { "10" });
	
		// 指定用 MyClass(string n) 執行 constructor
		ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
		object instance = ctor.Invoke(new object[] { "10" });
	}
}


class MyClass
{
	public MyClass(int n)
	{
		Console.WriteLine("Int parameter {0}", n);
	}

	public MyClass(string n)
	{
		Console.WriteLine("String parameter {0}", n);
	}
}
;