关于反射的一些有关问题,额,也许不是反射
关于反射的一些问题,额,也许不是反射?C# codepublic class a{}public class b:a{public int ipublic a(in
关于反射的一些问题,额,也许不是反射?
C# codepublic class a{}public class b:a{public int i;public a(int i){this.i=i}}public class c:a{public int i;public a(int i){this.i=i}}Type[] t=new Type[]{typeof(b),typeof(c),typeof(b)};//实例化List<a> result;
怎么对一个Type数组(t)里的每一项调用对应的带参数的构造函数进行实例化,然后将得到的对象存入一个对象数组(result)中?
[解决办法] Type[] t = new Type[] { typeof(b), typeof(c), typeof(b) };
List<a> results = new List<a>();
foreach (Type tp in t)
{
results.Add((a)tp.GetConstructor(new Type[] { typeof(Int32) }).Invoke(new object[] { 1 }));
}
[解决办法]简化下
Type[] t = new Type[] { typeof(b), typeof(c), typeof(b) };
List<a> results t.Select(tp => (a)tp.GetConstructor(new Type[] { typeof(Int32) }).Invoke(new object[] { 1 })).ToList();