在C#中获取子数组作为参考 [英] Getting subarray as reference in C#

查看:139
本文介绍了在C#中获取子数组作为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多函数以只读方式接受子数组(比如字符串)的输入.

I have a large number of functions accepting input of sub-arrays (let's say, string) in a read-only way.

我使用了Array.Copy(与MSDN等效的C ++ memmove)作为临时解决方法,但它在运行速度上遇到了严重的瓶颈.我有没有可以得到子数组的函数,比方说[0〜99]内的[4〜94],这样它就可以传递给function x(array[])作为参考,其中x内的数组由[0〜90]?

I used Array.Copy (C++ memmove equivalent from MSDN) as a temporary workaround, but it comes to a serious bottleneck on running speed. Is there any function I can get a sub-array, let's say [4~94] inside [0~99], such that it can be passed to a function x(array[]) as a reference where inside x the array is defined by [0~90]?

推荐答案

不幸的是,数组不能很好地与分区配合使用.获取子数组的唯一方法是创建原始数组的副本,这可能是瓶颈所在.

Unfortunately, arrays don't play nicely with partitioning. The only way to get a sub-array is by creating a copy of the original array, which is where the bottleneck probably is.

如果您可以修改函数以使用IEnumerable参数而不是数组,则可以使用LINQ轻松做到这一点:

If you can modify your functions to take IEnumerable parameters instead of arrays, you can do this easily with LINQ:

string[] values = { "foo", "bar", "baz", "zap" };
IEnumerable<string> subset = values.Skip(1).Take(2);

您还可以查看 ArraySegment ,但是(再次)需要更改函数的参数类型.

You could also look into ArraySegment, but this would (again) require changes to your functions' parameter types.

string[] values = { "foo", "bar", "baz", "zap" };
ArraySegment<string> segment = new ArraySegment<string>(values, 1, 2);

这篇关于在C#中获取子数组作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆