[英]Convert Bound List to Generic List<T>
I need to convert a bound (UnityEngine.Component) List to a generic (T) List, is this possible? 我需要将绑定的(UnityEngine.Component)列表转换为通用(T)列表,这可能吗? how?
怎么样?
I'm using Unity and C#, but I would like to know in general how one would do this. 我正在使用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);
thanks! 谢谢!
I assume that is the issue, I'm getting this runtime error... 我认为这是问题所在,我遇到了运行时错误...
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)
你有没有尝试过
List<T> newList = compList.OfType<T>().Select(x=>x).ToList()
Most likley cased by the fact that T and Component are different types: List<Component> compList
and compList as IEnumerable<T>
(this one will be null since compList is IEnumerable<Component>
not IEnumerable<T>
). 大多数
List<Component> compList
都以T和Component是不同类型的事实List<Component> compList
: List<Component> compList
和compList as IEnumerable<T>
(由于compList是IEnumerable<Component>
而不是IEnumerable<T>
该值为null)。
I think you want: 我想你要:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.