将引用传递给C#数组中的元素
时间:2020-03-05 18:44:03 来源:igfitidea点击:
我用建立一个字符串数组
string[] parts = string.spilt(" ");
并获得其中包含X个部分的数组,我想获得一个从element开始的字符串数组的副本
parts[x-2]
除了明显的蛮力方法(创建一个新数组并插入字符串)以外,在C#中还有更优雅的方法吗?
解决方案
回答
使用Array.Copy。它具有满足我们需要的重载:
Array.Copy (Array, Int32, Array, Int32, Int32) Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
回答
Array.Copy方法
我猜是这样的:
string[] less = new string[parts.Length - (x - 2)]; Array.Copy(parts, x - 2, less, 0, less.Length);
(消除了我确定存在的1个错误)。
回答
Array.Copy怎么样?
http://msdn.microsoft.com/zh-CN/library/aa310864(VS.71).aspx
Array.Copy Method (Array, Int32, Array, Int32, Int32) Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
回答
List<string> parts = new List<string>(s.Split(" ")); parts.RemoveRange(0, x - 2);
假设优化了List <string>(string [])以便使用现有数组作为后备存储而不是执行复制操作,这可能比执行数组复制要快。
回答
我记得回答这个问题,只是了解了一个新对象,它可以提供一种高性能的方法来做我们想要的事情。
看一下" ArraySegment <T>"。它会让我们做类似的事情。
string[] parts = myString.spilt(" "); int idx = parts.Length - 2; var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx);