リフレクションを使用してアイテムを一般リストに追加したいとします。 "DoSomething"メソッドでは、次の行を終了しようとしています。リフレクションを使用して一般リスト/コレクションにアイテムを追加する
エラーが発生しています。以下は
は私の完全なコード
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 });
:
MyBaseCollectionはどのようなタイプですか?リストに似ていますか? IEnumerableを実装するすべてのクラスでAddメソッドが保証されているわけではありません。 –
JoeyRobichaud
@JoeRobich:MyBaseCollectionはIListから派生した独自のコレクション実装です。リストの偶数回答は私の問題を解決するはずです... –
kayak