所以基本上我为数组类型编写了我的小 Add
扩展方法。
using System;
using System.Linq;
public static class Extensions
{
public static void Add<T>(this T[] _self, T item)
{
_self = _self.Concat(new T[] { item }).ToArray();
}
}
public class Program
{
public static void Main()
{
string[] test = { "Hello" };
test = test.Concat(new string[] { "cruel" }).ToArray();
test.Add("but funny");
Console.WriteLine(String.Join(" ", test) + " world");
}
}
输出应该是 Hello cruel but funny world
,但是 but funny
永远不会在扩展方法中连接起来。
在扩展中编辑同一个数组似乎也不起作用:
using System;
using System.Linq;
public static class Extensions
{
public static void Add<T>(this T[] _self, T item)
{
Array.Resize(ref _self, _self.Length + 1);
_self[_self.Length - 1] = item;
}
}
public class Program
{
public static void Main()
{
string[] test = { "Hello" };
test = test.Concat(new string[] { "cruel" }).ToArray();
test.Add("but funny");
Console.WriteLine(String.Join(" ", test) + " world");
}
}
我在这里做错了什么,我怎样才能将它用作扩展?
.dotNet fiddle :https://dotnetfiddle.net/9os8nY或 https://dotnetfiddle.net/oLfwRD
(如果能找到一种方法让我可以继续调用 test.Add("item");
)
最佳答案
你正在为参数分配一个新的引用,它不会改变实际的数组,除非你将它作为 ref
参数传递。由于这是一种扩展方法,因此它不是一种选择。所以考虑使用正常的方法:
public static void Add<T>(ref T[] _self, T item)
{
_self = _self.Concat(new T[] { item }).ToArray();
}
Add(ref test, "but funny");
或者,如果您坚持使用扩展方法,则需要将数组作为第二个参数才能使用 ref:
public static void AddTo<T>(this T item, ref T[] arr, )
{
arr = arr.Concat(new T[] { item }).ToArray();
}
"but funny".AddTo(ref test);
Array.Resize
不起作用。因为它更改了 _self
,而不是 test
数组。现在,当您传递不带 ref
关键字的引用类型时,将复制该引用。它是这样的:
string[] arr1 = { "Hello" };
string[] arr2 = arr1;
现在,如果您为 arr2
分配一个新引用,它不会更改 arr1
的引用。Array.Resize
正在做什么是因为无法调整数组大小,它创建一个新数组并将所有元素复制到一个新数组,并将该新引用分配给参数(_self
在这个case). 所以它改变了 _self
指向的地方,但是因为 _self
和 test
是两个不同的引用(比如 arr1
和 arr2
),更改其中一个不会影响另一个。
另一方面,如果像我的第一个示例那样将数组作为 ref
传递给您的方法,Array.Resize
也会按预期工作,因为在这种情况下引用不会被复制:
public static void Add<T>(ref T[] _self, T item)
{
Array.Resize(ref _self, _self.Length + 1);
_self[_self.Length - 1] = item;
}
关于c# - 在扩展方法中更改数组大小不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799341/