參考網址: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);
}
}
浙公網安備 33010602011771號