将绑定列表转换为泛型列表

本文关键字:列表 泛型 绑定 转换 | 更新日期: 2023-09-27 18:35:05

我需要将绑定(UnityEngine.Component)列表转换为通用(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)

将绑定列表转换为泛型列表<T>

你试过吗

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

最像的情况是 T 和组件是不同的类型: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);