我想使用反射将项目添加到通用列表。在“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(??????)
}
}
}
}
有什么想法/建议吗?
最佳答案
我想你想要:
// Cast to IEnumerable<MyBaseClass> isn't helping you, so why bother?
object cln = pi.GetValue(this, null);
// Create myBaseClassInstance.
// (How will you do this though, if you don't know the element-type?)
MyBaseClass myBaseClassInstance = ...
// Invoke Add method on 'cln', passing 'myBaseClassInstance' as the only argument.
pi.PropertyType.GetMethod("Add").Invoke(cln, new[] { myBaseClassInstance } );
由于您不知道集合的元素类型是什么(可能是汽车、自行车、自行车等),您会发现很难找到有用的转换。例如,虽然您说该集合肯定会实现 IList<SomeMyBaseClassSubType>
,自 IList<T>
以来,这并没有多大帮助不是协变的。当然,转换到IEnumerable<MyBaseClass>
应该成功,但这对您没有帮助,因为它不支持突变。另一方面,如果您的集合类型实现了非泛型 IList
或 ICollection
类型,转换到那些可能会派上用场。
但是如果您确定该集合将实现 IList<Car>
(即你事先知道集合的元素类型),事情更容易:
// A much more useful cast.
IList<Car> cln = (IList<Car>)pi.GetValue(this, null);
// Create car.
Car car = ...
// The cast helped!
cln.Add(car);
关于c# - 使用反射将项目添加到通用列表/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910256/