我需要將綁定(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)
框架和語言吧?一些代碼? – yamen
什麼行引發異常?更新了 – Amy
,但我想大致瞭解如何在C#中完成此操作。 – user1414025