声明&amp;迭代集合<t> </t>

时间:2012-09-06 14:31:44

标签: c# generics boxing

我有名字&amp;对象的类型和方法名称。 理想情况下,我想实例化对象&amp;调用方法。一切都很顺利,但我在尝试处理结果时遇到错误。

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);
        }
    }

我在“调用”行中收到错误说 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或类似的?

由于

1 个答案:

答案 0 :(得分:1)

类型T似乎必须始终提供一个名称存储在ods.SelectMethod中的方法和多个属性。如果T必须实现包含此方法的接口,则可以使用以下方法将IterateCollection<T>约束到该接口:

   private static void IterateCollection<T>(T instance, DropDownList ddl)
       where T: IMyInterface 

假设您不能这样做,请使用LinkedList<object>。您正在使用反射调用方法,因此泛型不会为您提供任何语法帮助。