2012-05-24 72 views
1

我需要將綁定(UnityEngine.Component)列表轉換爲通用(T)列表,這可能嗎?怎麼樣?將綁定列表轉換爲通用列表<T>

我使用Unity和C#,但我想知道一般如何做到這一點。

 List<Component> compList = new List<Component>(); 
     foreach(GameObject obj in objects) // objects is List<GameObject> 
     { 
      var retrievedComp = obj.GetComponent(typeof(T)); 
      if(retrievedComp != null) 
       compList.Add(retrievedComp); 
     } 

     List<T> newList = new List<T>(compList as IEnumerable<T>); // ERROR HERE 

     foreach(T n in newList) 
      Debug.Log(n); 

謝謝!

我認爲這是問題,我得到這個運行時錯誤...

ArgumentNullException: Argument cannot be null. 
Parameter name: collection 
System.Collections.Generic.List`1[TestPopulateClass].CheckCollection (IEnumerable`1 collection) 
System.Collections.Generic.List`1[TestPopulateClass]..ctor (IEnumerable`1 collection) 
DoPopulate.AddObjectsToList[TestPopulate] (System.Reflection.FieldInfo target) (at Assets/Editor/ListPopulate/DoPopulate.cs:201) 
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) 
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation. 
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) 
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) 
DoPopulate.OnGUI() (at Assets/Editor/ListPopulate/DoPopulate.cs:150) 
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) 
+1

框架和語言吧?一些代碼? – yamen

+0

什麼行引發異常?更新了 – Amy

+0

,但我想大致瞭解如何在C#中完成此操作。 – user1414025

回答

1

你試過

List<T> newList = compList.OfType<T>().Select(x=>x).ToList() 
+0

; ? – user1414025

+0

謝謝!那麼做了這個工作,它是如何工作的? – user1414025

+0

[OfType ](http://msdn.microsoft.com/en-us/library/bb360913.aspx)和[鑄造](http://msdn.microsoft.com/en-us/library/bb341406)在最終投影中將對象投射到T上。 – Tilak

0

的事實,T和分量是不同的大多數likley套管類型:List<Component> compListcompList as IEnumerable<T>(由於compList是IEnumerable<Component>而不是IEnumerable<T>,因此它將爲空)。

我想你想:

List<T> compList = new List<T>(); // +++ T instead of GameObject 
    foreach(GameObject obj in objects) // objects is List<GameObject> 
    { 
     // ++++ explict cast to T if GetComponent does not return T 
     var retrievedComp = (T)obj.GetComponent(typeof(T)); 
     if(retrievedComp != null) 
      compList.Add(retrievedComp); 
    } 

    List<T> newList = new List<T>(compList as IEnumerable<T>); // ERROR HERE 

    foreach(T n in newList) 
     Debug.Log(n); 
+0

我收到了一些錯誤,'無法將類型UnityEngine.Component轉換爲T用於投射'。而「參數#1不能轉換對象表達式類型到T」處添加 – user1414025

+0

提拉克的答案(+1)包含正確執行的代碼,我試圖maually修復。對於手動implemetation工作對T正確適當的限制應設置(likly'其中T:Component')... –

+0

感謝澄清! – user1414025