我想将一个 C# 数组的子集传递给一个方法。我不在乎该方法是否会覆盖数据,因此希望避免创建副本。
有没有办法做到这一点?
谢谢。
我想将一个 C# 数组的子集传递给一个方法。我不在乎该方法是否会覆盖数据,因此希望避免创建副本。
有没有办法做到这一点?
谢谢。
更改方法以采用IEnumerable<T>
or ArraySegment<T>
。
然后你可以通过new ArraySegment<T>(array, 5, 2)
在 C# 7.2 中,我们拥有Span<T>
. 您可以对数组使用扩展方法AsSpan<T>
并将其传递给方法,而无需复制切片部分。例如:
Method( array.AsSpan().Slice(1,3) )
您可以使用以下类。请注意,您可能需要修改它,具体取决于您endIndex
是要包含还是排他。您还可以修改它以获取开始和计数,而不是开始和结束索引。
我故意没有添加可变方法。如果您特别想要它们,那么添加起来很容易。IList
如果添加可变方法,您可能还想实现。
public class Subset<T> : IReadOnlyList<T>
{
private IList<T> source;
private int startIndex;
private int endIndex;
public Subset(IList<T> source, int startIndex, int endIndex)
{
this.source = source;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public T this[int i]
{
get
{
if (startIndex + i >= endIndex)
throw new IndexOutOfRangeException();
return source[startIndex + i];
}
}
public int Count
{
get { return endIndex - startIndex; }
}
public IEnumerator<T> GetEnumerator()
{
return source.Skip(startIndex)
.Take(endIndex - startIndex)
.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
数组在大小上是不可变的(即您不能更改数组的大小),因此您只能传递原始数组的减法副本。作为选项,您可以将原始数组之外的两个索引传递到方法中,并在另外两个索引的基础上进行操作。
您可以使用 Linq take funktion 并根据需要从数组中获取任意数量的元素
var yournewarray = youroldarray.Take(4).ToArray();