BindingList<T> and reflection?
If I have a business object, Order, where Order contains OrderDetails, where OrderDetails is a BindingList<OrderDetail>. How can I create this using relfection?
I have an object builder that dynamically creates the SQL statements and gets a list of order details. Now I need to place those order details in the BindingList<OrderDetail> details member of my object?
Code:
/// obj - Container object which holds the BindingList<T> object.
/// property - The PropertyInfo object for the BindingList<T> object.
/// targetType - The type of object that the data reader has and the BindingList<T> should contain.
/// rdr - The date reader with the records?
void LoadObjects(ObjectBase obj, PropertyInfo property, Type targetType, IDataReader rdr)
{
//// I need to create the binding list???????
BindingList<????targetType????> list = Activator.CreateInstance(????);
while(rdr.Read())
{
ObjectBase newObj = Activator.CreateInstance(targetType);
FillObject(newObj, rdr);
list.Add(newObj);
}
property.SetValue(obj, list, null);
}
Any help at all with this?
Mike B
Re: BindingList<T> and reflection?
try making LoadObjects generic and pass your generic type parameter in as a type parameter to the method instead of as a method parameter.
failing that, you'll have to do it all by reflection instead of creating a known type and calling methods directly on it.
Re: BindingList<T> and reflection?
To create an instance of generic type at runtime, you need Type's MakeGenericType() method.
In your case:
Code:
Type type = typeof(BindingList<>).MakeGenericType(targetType);
Re: BindingList<T> and reflection?
Quote:
Originally Posted by
boudino
To create an instance of generic type at runtime, you need Type's MakeGenericType() method.
In your case:
Code:
Type type = typeof(BindingList<>).MakeGenericType(targetType);
Thanks, that works!
[Edit]
Ok, it works, but how to I assign it to a property of the "parent" object class. The IBindingList needs an explicit cast. Any ideas?
Mike Bujak
Re: BindingList<T> and reflection?
Quote:
Originally Posted by
MadHatter
try making LoadObjects generic and pass your generic type parameter in as a type parameter to the method instead of as a method parameter.
failing that, you'll have to do it all by reflection instead of creating a known type and calling methods directly on it.
Thanks for the reply. What you said works, but I am afraid it doesn't allow me to do all I need to do. There are times when I am loading an object, I may also need to "Eagerly" load some of its child objects and collections, at this point, the type of object is unknown and cannot be passed as a parameter.
Mike B
Re: BindingList<T> and reflection?
Quote:
Originally Posted by
MikeB
Thanks, that works!
[Edit]
Ok, it works, but how to I assign it to a property of the "parent" object class. The IBindingList needs an explicit cast. Any ideas?
Mike Bujak
Should I just declare the members as IBindingList instead of explicit types?