31
1
using System;
2
using System.Reflection;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
Type type = typeof(MyClass);
9
// 使用 Activator.CreateInstance
10
Activator.CreateInstance(type, new object[] { 10 });
11
Activator.CreateInstance(type, new object[] { "10" });
12
13
// 指定用 MyClass(string n) 執行 constructor
14
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
15
object instance = ctor.Invoke(new object[] { "10" });
16
}
17
}
18
19
20
class MyClass
21
{
22
public MyClass(int n)
23
{
24
Console.WriteLine("Int parameter {0}", n);
25
}
26
27
public MyClass(string n)
28
{
29
Console.WriteLine("String parameter {0}", n);
30
}
31
}
Cached Result