我有一个 Foo 对象数组。如何删除数组的第二个元素?
我需要类似的东西RemoveAt()
但对于常规数组。
如果您不想使用列表:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
你可以尝试这个我没有实际测试过的扩展方法:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
并像这样使用它:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)