从offset开始获取数组

Nef*_*zen 10 c# arrays

我正在使用C#,而且我无法从像C++这样的特定点开始发送数组,这很烦人.

假设这段代码:

int[] array = new int[32];
foobar (array + 4); //send array starting from the 4th place.
Run Code Online (Sandbox Code Playgroud)

这是C#的一种奇怪的语法,因为我们没有任何可用的指针,但肯定有办法吗?有.Skip(),但我认为它产生了一个新的数组,这是我不喜欢的.

我有什么选择?

tva*_*son 17

您可能希望将其作为IEnumerable<int>数组而不是数组传递.然后,您可以使用skip,它只会将迭代器移动到跳过的元素数量上.使用这种方式,您不必使用ToArray()并创建相关数组部分的副本.当然,IEnumerable可能不适合您想要做的事情,但这很难从您的问题中分辨出来.

public void FooBar( IEnumerable<int> bar )
{
  ...
}

int[] array = new int[32];
FooBar( array.Skip(4) );
Run Code Online (Sandbox Code Playgroud)

  • 零数组已经实现了IEnumerable <T> (6认同)
  • 将数组转换为可枚举的开销是多少? (2认同)
  • http://msdn.microsoft.com/en-us/library/system.array.aspx在.NET Framework 2.0版中,Array类实现了System.Collections.Generic.IList(T),System.Collections.Generic .ICollection(T)和System.Collections.Generic.IEnumerable(T)泛型接口.这些实现在运行时提供给数组,因此文档构建工具不可见. (2认同)
  • 在一百万年里不会想到这种方法.真的很优雅.+1 (2认同)
  • 我很确定它会复制枚举中的元素并将其作为数组返回. (2认同)

Ed *_* S. 1

您可以将偏移量作为参数传递给函数本身。然后,该函数将简单地循环遍历从 [array + offset] 到 array.Length 的元素。或者将子数组复制到新数组中,但这可能不是最佳的。