我想使用反射将项目添加到通用列表。在方法“DoSomething”,我想完成以下行,使用反射将项目添加到通用列表/集合
pi.PropertyType.GetMethod("Add").Invoke(??????)
但我得到不同种类的错误。
下面是我完整的代码
public class MyBaseClass
{
public int VechicleId { get; set; }
}
public class Car:MyBaseClass
{
public string Make { get; set; }
}
public class Bike : MyBaseClass
{
public int CC { get; set; }
}
public class Main
{
public string AgencyName { get; set; }
public MyBaseCollection<Car> lstCar {get;set;}
public void DoSomething()
{
PropertyInfo[] p =this.GetType().GetProperties();
foreach (PropertyInfo pi in p)
{
if (pi.PropertyType.Name.Contains("MyBaseCollection"))
{
//Cln contains List<Car>
IEnumerable<MyBaseClass> cln = pi.GetValue(this, null) as IEnumerable<MyBaseClass>;
**//Now using reflection i want to add a new car to my object this.MyBaseCollection**
pi.PropertyType.GetMethod("Add").Invoke(??????)
}
}
}
}
任何意见/建议?
什么类型是MyBaseCollection?它是否类似于名单?并非所有实现IEnumerable的类都保证有一个Add方法。 –
JoeyRobichaud
2011-02-05 23:10:03
@JoeRobich:MyBaseCollection是自己的收集实现,它是派生自IList,即使答案为列表应解决我的问题... –
kayak
2011-02-05 23:14:49