haizzh

博客园 首页 新随笔 联系 订阅 管理

参考网址:http://stackoverflow.com/questions/315231/using-reflection-to-set-a-property-with-a-type-of-listcustomclass

遇到的问题:需要反射一个方法,但是它的参数也是程序集里的一个list数组。当调用一般的传参过程会报错,使用下述的语法创建list数组可以当参数传入。
class Foo { public string Bar { get; set; } } class Program { static void Main() { Type type = typeof(Foo); // possibly from a string IList list = (IList) Activator.CreateInstance( typeof(List<>).MakeGenericType(type)); object obj = Activator.CreateInstance(type); type.GetProperty("Bar").SetValue(obj, "abc", null); list.Add(obj); } }
posted on 2017-01-17 16:32  haizzh  阅读(446)  评论(0编辑  收藏  举报