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

发布于 2025-01-19 23:43:48 字数 621 浏览 4 评论 0原文

我想将数组传递到C#中具有特定索引的函数,就像我们在C ++中一样,类似以下内容:

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

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

在这种情况下,假设a以基础地址1000,然后b为1000+(sizeof(int)*3)。此 link 使用 skip()函数调用,但在这种情况下,b应该是类型iEnumerable< int>以及在调用skip() skip()代码>带有toArray()它创建一个具有不同基本地址的副本,但我想将同一数组传递给function foo。我们如何在C#中做到这一点?

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#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

血之狂魔 2025-01-26 23:43:48

这在这里得到了回答:
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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文