[英]C# Passing array with specific array index
I want to pass an array to a function with specific index in C#, like we do in C++, something like below:我想将一个数组传递给 function,具体索引为 C#,就像我们在 C++ 中所做的那样,如下所示:
void foo(int* B) {
// do something;
}
int main() {
int A[10];
foo(A + 3);
}
In this case suppose A
starts with base address 1000
, then B would be 1000+(sizeof(int)*3)
.在这种情况下,假设
A
以基地址1000
开头,那么 B 将是1000+(sizeof(int)*3)
。 The answer in this link uses Skip()
function call but in this case B
should be of type IEnumerable<int>
and on calling Skip()
with ToArray()
it creates a copy with different base address, but I want to pass this same array to function foo.此链接中的答案使用
Skip()
function 调用,但在这种情况下, B
应该是IEnumerable<int>
类型,并且在使用ToArray()
调用Skip()
时,它会创建一个具有不同基地址的副本,但我想传递相同的阵列到 function foo。 How can we do that in C#?我们如何在 C# 中做到这一点?
This has been answered here: C# Array slice without copy这已经在这里得到回答: C# Array slice without copy
You can use ArraySegment or Span to achieve this您可以使用 ArraySegment 或 Span 来实现此目的
public static void Main()
{
int[] arr1 = new int[] {2, 5, 8, 10, 12};
int[] arr2 = new int[] {10, 20, 30, 40};
DoSomethingWithSegmentReference(new ArraySegment<int>(arr1, 2, arr1.Length - 2));
DoSomethingWithSpanReference(arr2.AsSpan().Slice(1, arr2.Length - 1));
}
private static void DoSomethingWithSegmentReference(ArraySegment<int> slice){
for(int i = 0; i < slice.Count; i++)
slice[i] = slice[i] * 2;
}
private static void DoSomethingWithSpanReference(Span<int> slice){
for(int i = 0; i < slice.Length; i++)
slice[i] = slice[i] * 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.