【问题标题】:Failing to cast to generic array无法转换为通用数组
【发布时间】:2016-12-02 11:16:07
【问题描述】:

你好我有以下扩展方法

    public static T[] GetComponentsOfType<T>(this GameObject source) where T : MonoBehaviour
    {
        Component[] matchingComponents = source.GetComponents<Component>().Where(comp => comp is T).ToArray();
        T[] castedComponents = new T[matchingComponents.Length];
        for (int i = 0; i < matchingComponents.Length; i++)
        {
            castedComponents[i] = (T) matchingComponents[i];
        }
        return castedComponents;
    }

这完全没问题,但是我试图将它缩短一行

 return (T[]) source.GetComponents<Component>().OfType<T>().Cast<Component>().ToArray();

显然这条线无法将Component[] 转换为T[],但是当我分别转换每个元素时它可以工作(第一个示例)。这是为什么呢?

【问题讨论】:

  • 嗯,是的——如果你创建了一个Component[],那不是一个FooComponent[]或任何T。为什么不直接使用OfType&lt;T&gt;().ToArray()?你为什么打电话给Cast&lt;Component&gt;()
  • Cast&lt;Component&gt;() 没有意义。如果你想要T's,为什么要再次将其转换为Component
  • Resharper 让我这样做@JonSkeet :)

标签: c# arrays generics casting


【解决方案1】:

你可以写:

source.GetComponents<Component>().OfType<T>().ToArray();

在一行中完成。

转换失败,因为您将两种不匹配的类型转换为组件数组和 T 数组,这是无效的。

【讨论】:

  • 您希望Select 做什么?
【解决方案2】:

您应该只使用OfType&lt;&gt;。在您的解决方案中,您又回到了Component,它不能转换为 T[],所以这就是问题所在。

OfType&lt;&gt; 已经投射了它。这就像Where(item =&gt; item is T).Cast&lt;T&gt;()的替代品

return source.GetComponents<Component>().OfType<T>().ToArray();

【讨论】:

  • 确实return source.GetComponents&lt;Component&gt;().OfType&lt;T&gt;().ToArray(); 完全可以胜任这项任务,谢谢您的快速响应!
  • @JeroenvanLangen:但是你仍然得到了实际的演员表操作员(T[])。这是不必要的,因为ToArray() 的返回类型已经是T[]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 2013-05-20
相关资源
最近更新 更多