传递数组而不是副本c#

时间:2014-01-24 16:47:44

标签: c#

如何在不复制数据的情况下传递数组? 我有:

private readonly IList<GameObjectTemplate> mMapGameObjects;

    public GameObjectTemplate[] GetObjects(GameObjectType type)
{
    List<GameObjectTemplate> tempObjects = new List<GameObjectTemplate>();

    for (int i = 0; i < mMapGameObjects.Count; i++)
    {
        if (mMapGameObjects[i].Type == type)
        {
            tempObjects.Add(mMapGameObjects[i]);
        }
    }

    return tempObjects.ToArray();
}

所以我想只选择某种类型的对象并返回相同的数组而不是副本。是否可能?

1 个答案:

答案 0 :(得分:3)

除非您确实需要数组,否则请考虑返回IEnumerable<GameObjectTemplate>

public IEnumerable<GameObjectTemplate> GetObjects(GameObjectType type)
{
   return mMapGameObjects.Where(m => m.Type == type);
}