我有对象的名称和类型以及方法名称。理想情况下,我想实例化对象并调用方法。一切都很好,但我在尝试处理结果时遇到错误。
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);
}
}
我在“Invoke”行中收到错误消息
System.InvalidCastException :
Unable to cast object of type 'System.Collections.Generic.LinkedList``1[Business.Objects.MyType]' to type 'System.Collections.Generic.ICollection
1[System.Object]'。
我希望能够遍历集合。我怎样才能做到这一点?如何创建 LinkedList 或类似的?
谢谢