向下转换整个数组

问题描述

在 Unity 中,我试图检测对象上文本类型的所有组件

this.GetComponents(typeof(Text))

但它返回一个组件数组。 因为我知道每个组件都必须是文本类型,所以我应该能够将其向下转换。 我试图显式转换它

Text[] a = (Text[])this.GetComponents(typeof(Text));

但这没有用。 Text 是组件的派生类,但我不知道如何向下转换数组,以便我可以使用与文本类型关联的方法。有人可以告诉我如何将数组转换为 Text 类型之一吗?

解决方法

the docs 开始,您可以使用泛型方法 GetComponents 而无需对每个进行类型转换。

using UnityEngine;

public class Example : MonoBehaviour
{
    void Start()
    {
        HingeJoint[] hinges = GetComponents<HingeJoint>();
        for (int i = 0; i < hinges.Length; i++)
        {
            hinges[i].useSpring = false;
        }
    }
}
,

您应该使用通用语法:this.GetComponents<Text>()。这将返回 Text[],因此无需再进行转换。