扩展方法怎么实现 小白求解

MichaelGLX 2023-01-10 15:27:41

       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对象。

 

...全文
205 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanghui0380 2023-01-10
  • 打赏
  • 举报
回复

数组是值类型,而且不可修改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);
        }

MichaelGLX 2023-01-10
  • 举报
回复
@wanghui0380 谢谢,扩展方法没法实现与我写的那种调用需求吗?
詹姆士x 2023-01-16
  • 举报
回复
@MichaelGLX 扩展方法不能改变调用的变量本身

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧