【发布时间】:2015-01-06 13:07:33
【问题描述】:
所以基本上我为数组类型编写了我的小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 小提琴:https://dotnetfiddle.net/9os8nY 或 https://dotnetfiddle.net/oLfwRD
(如果能找到一种方法让我可以继续通话test.Add("item");,那就太好了)
【问题讨论】:
-
不能使用扩展方法来完成,因为 this 和 ref 关键字不能一起使用。您可以将新数组作为结果返回并进一步使用。
-
您应该真正使用
List<>,如果您在某些时候需要数组,只需执行.ToArray()。您正在尝试做List<>已经在做的事情。 -
@Franck 我正在使用 Unity3D,编辑器以更好的方式处理数组(实际上它根本不会处理 List),出于性能原因,它们应该保留数组,因此扩展方法只会在编辑器中被调用,而不是游戏本身。
-
@modiX 在这种情况下,您应该将 Unity 标签添加到问题中。
List<>根据微软源代码实际上使用一个数组来存储数据,所以List<string>与string[]是一回事。不同之处在于少数额外属性的分配大小。访问数据的速度相同,并且添加由 Microsoft 自己优化。
标签: c# arrays unity3d extension-methods concat