2012-09-06 55 views
1

我有名字&對象的類型和方法名稱。 理想情況下,我想實例化調用該方法的對象&。所有這一切都很好,但我正在嘗試處理結果時出錯。Declare&Iterate collection <T>

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或類似的?

由於

+0

我該如何創建'LinkedList '? – ShrapNull

回答

1

看來,類型T必須始終提供與存儲在ods.SelectMethod和多個屬性的名稱的方法。如果T必須實現包含此方法的接口,可以使用約束IterateCollection<T>到該接口:

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

假設你不能做到這一點,使用LinkedList<object>。您正在調用使用反射的方法,所以泛型不會給你任何語法上的幫助。

+0

我想在不使用接口方法的情況下實現此目的。我仍然無法通過InvalidCastException。這可能是我嘗試這種方式嗎?非常感謝 – ShrapNull

+0

@ user1652234我逃脫了'LinkedList ',這是我以前忘記做的。使用這項工作嗎? – akton

+0

LinkedList 沒有工作並導致相同的錯誤。 – ShrapNull

相關問題