将绑定列表转换为通用列表<t> </t>

时间:2012-05-24 03:26:43

标签: c# list generics unity-container

我需要将绑定(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)

2 个答案:

答案 0 :(得分:1)

你试过吗

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

答案 1 :(得分:0)

最有可能的原因是T和Component是不同的类型:List<Component> compListcompList as IEnumerable<T>(由于compList为IEnumerable<Component>而不是IEnumerable<T>,因此该值为null。

我想你想要:

    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);