我正在尝试优化用 C# 制作的类似蛇的游戏,其中我有一个 ArrayList,其中包含存储的所有蛇体部分。我需要能够像切割一副纸牌一样切割这个 ArrayList,我会把这副纸牌的顶部放在底部。这应该有助于澄清。
01234 => 01 234 => 234 01 => 23401
这个 ArrayList 可以大到 300 个元素,我需要让这个操作尽可能便宜,因为这个游戏是针对移动设备的。
最佳答案
使用 Array.Copy
应该是最快的方法。但它要求您使用 T[]
数组,而不是 ArrayList
。
public void CutTop<T>(this T[] source, int nbOfItemsToCut) {
if(source == null)
throw new ArgumentNullException("source");
var length = source.Length;
if(nbOfItemsToCut > length)
throw new ArgumentException("nbOfItemsToCut");
var temp = new T[nbOfItemsToCut];
Array.Copy(source, temp, nbOfItemsToCut);
Array.Copy(source, nbOfItemsToCut, source, 0, length - nbOfItemsToCut);
Array.Copy(temp, 0, source, length - nbOfItemsToCut, nbOfItemsToCut);
}
关于c# - C#中的数组切割和合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124402/