c#使用扩展方法移除数组的一个元素
时间: 2024-05-10 21:15:57 浏览: 14
可以使用扩展方法来移除数组的一个元素,具体实现如下:
```csharp
public static class ArrayExtensions
{
public static T[] RemoveAt<T>(this T[] source, int index)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (index < 0 || index >= source.Length)
{
throw new ArgumentOutOfRangeException(nameof(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;
}
}
```
使用方法如下:
```csharp
int[] arr = { 1, 2, 3, 4, 5 };
arr = arr.RemoveAt(2); // 移除索引为2的元素
```
上述代码会将数组 `arr` 中索引为2的元素(即数字3)移除,返回一个新的数组,新数组的长度为原数组长度减1。