繁体   English   中英

C# 传递具有特定数组索引的数组

[英]C# Passing array with specific array index

我想将一个数组传递给 function,具体索引为 C#,就像我们在 C++ 中所做的那样,如下所示:

void foo(int* B) {
// do something;
}

int main() {
int A[10];
foo(A + 3);
}

在这种情况下,假设A以基地址1000开头,那么 B 将是1000+(sizeof(int)*3) 链接中的答案使用Skip() function 调用,但在这种情况下, B应该是IEnumerable<int>类型,并且在使用ToArray()调用Skip()时,它会创建一个具有不同基地址的副本,但我想传递相同的阵列到 function foo。 我们如何在 C# 中做到这一点?

这已经在这里得到回答: C# Array slice without copy

您可以使用 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.

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