I have the name & type of an object and the method name.
Ideally I would like to instantiate the object & call the method. All is well with that, but I am getting an error trying to process the results.
private void GetData(DropDownList ddl)
{
ObjectDataSource ods = (ObjectDataSource)ddl.DataSourceObject;
System.Reflection.Assembly assembly = typeof(ExistingObject).Assembly;
Type type = assembly.GetType(ods.SelectMethod);
var instance = Activator.CreateInstance(type);
IterateCollection(instance, ddl);
}
private static void IterateCollection<T>(T instance, DropDownList ddl)
{
ObjectDataSource ods = (ObjectDataSource)ddl.DataSourceObject;
Type type = instance.GetType();
MethodInfo methodInfo = type.GetMethod(ods.SelectMethod);
LinkedList<T> col = (LinkedList<T>)methodInfo.Invoke(null, new object[] { (T)instance });
foreach (T o in col)
{
string textfield = Convert.ToString(GetPropValue(o, ddl.DataTextField));
string valuefield = Convert.ToString(GetPropValue(o, ddl.DataValueField));
ListItem li = new ListItem(textfield, valuefield);
if ((bool?)GetPropValue(o, "Active") != true)
li.Attributes.CssStyle.Add("background-color", "gray");
ddl.Items.Add(li);
}
}
I am getting an error on the “Invoke” line saying
System.InvalidCastException :1[System.Object]’.
Unable to cast object of type 'System.Collections.Generic.LinkedList``1[Business.Objects.MyType]' to type 'System.Collections.Generic.ICollection
I would like to be able to iterate through the collection. How can I do this?
How can I create a LinkedList or similar?
Thanks
It appears that the type
Tmust always provide a method with the name stored inods.SelectMethodand multiple properties. IfThas to implement an interface containing this method, you can constrainIterateCollection<T>to that interface using:Assuming you cannot do that, use a
LinkedList<object>. You are invoking the methods using reflection so generics will not give you any syntactic assistance.