110,534
社区成员
public static void Resize<T>(this T[] arr, int size)
{
if (size <= 0)
{
arr = null;
return;
}
if (arr != null && arr.Length > 0)
{
if (size == arr.Length)
{
return;
}
else
{
int num = size > arr.Length ? arr.Length : size;
T[] list = new T[size];
Array.Copy(arr, list, num);
arr = list;
}
}
else
{
arr = new T[size];
}
}
//调用
int[] values = new int[5];
values.Resize(3);
//希望改变数组长度,但是这样并未实现。长度还是5, 封装的扩展方法不知道怎么改变 arr对象。
数组是值类型,而且不可修改size
请参考Array.Resize()
官方实现,看看官方的代码,官方也只能用ref 来处理Array
public static void Resize<T>([NotNull] ref T[]? array, int newSize)
{
if (newSize < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
T[]? larray = array; // local copy
if (larray == null)
{
array = new T[newSize];
return;
}
if (larray.Length != newSize)
{
// Due to array variance, it's possible that the incoming array is
// actually of type U[], where U:T; or that an int[] <-> uint[] or
// similar cast has occurred. In any case, since it's always legal
// to reinterpret U as T in this scenario (but not necessarily the
// other way around), we can use Buffer.Memmove here.
T[] newArray = new T[newSize];
Buffer.Memmove<T>(
ref MemoryMarshal.GetArrayDataReference(newArray),
ref MemoryMarshal.GetArrayDataReference(larray),
(uint)Math.Min(newSize, larray.Length));
array = newArray;
}
Debug.Assert(array != null);
}