【发布时间】:2013-05-14 17:49:51
【问题描述】:
class Building {
}
class Home: Building {
}
private List<Building> buildings;
public T[] FindBuildings<T>() {
return buildings.FindAll(x => x is T).ToArray() as T[];
}
我有一个列表来保存地图上的所有建筑物,并编写一个函数来查找特定的建筑物类型。
我想使用FindBuildings<Home>() 来获取一个包含地图上所有住宅建筑的数组,但是当我运行代码时,我发现函数总是返回null,似乎as 不起作用。这是否意味着as 不能使用泛型类型参数?
所以,我改一下代码:
private List<Building> buildings;
public Building[] FindBuildings<T>() {
return buildings.FindAll(x => x is T).ToArray();
}
使用FindBuildings<Home>() as Home[] 访问地图上的住宅建筑。但是......它仍然为空。
我看到了一个Unity3d的例子,给我看使用'as'转换数组类型,为什么我失败了?
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void OnMouseDown() {
HingeJoint[] hinges = FindObjectsOfType(typeof(HingeJoint)) as HingeJoint[];
foreach (HingeJoint hinge in hinges) {
hinge.useSpring = false;
}
}
}
【问题讨论】:
-
您不能将
Bulding[]转换为House[],即使您知道源数组的每个条目都是House。 -
@Dirk 该死的,没关系-我的投射方向倒退了-我的错