很久没有写反射了,来整理一下呗.
创建 Type
public class Abc {} var type = typeof(Abc); // class to type var type2 = new Abc().GetType(); // instance to type
有泛型的
public class Abc<T, U> {} var type = typeof(Abc<,>).MakeGenericType(new[] { typeof(string), typeof(string) });
创建实例
public class Abc{ public string name { get; set; } } var abc = Activator.CreateInstance(typeof(Abc)) as Abc;
有参数的
public class Abc { public Abc(string name) { } } var abc = Activator.CreateInstance(typeof(Abc), new object[] { "name" }) as Abc;
有可选参数的
public class Abc { public Abc(string name = "dada") { } } var abc = Activator.CreateInstance(typeof(Abc), BindingFlags.OptionalParamBinding, null, new object[] { Type.Missing }, CultureInfo.CurrentCulture) as Abc;
几个点留意一下
一定要有 BindingFlags.OptionalParamBinding, 也有人放完. BindingFlags.CreateInstance |
BindingFlags.Public |
BindingFlags.
Instance
Type.Missing 表示没有传 value
CultureInfo.CurrentCulture 不清楚用来干嘛.