简体   繁体   中英

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:

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) . 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. How can we do that in C#?

This has been answered here: C# Array slice without copy

You can use ArraySegment or Span to achieve this

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM