获得子阵列从现有阵列 [英] Getting a sub-array from an existing array
问题描述
我有10个元件的阵列的X.我想创建一个包含X中开始,在指数3的所有元素的数组,结束于指数7。当然,我可以很容易地编写一个循环,会为我做的,但我想保持我的code作为干净越好。有没有一种方法,在C#中,可以做到这一点对我?
喜欢的东西(假code):
阵列NewArray = oldArray.createNewArrayFromRange(INT BeginIndex,INT endIndex的)
Array.Copy
不适合我的需要。我需要在新的数组中的项目是克隆。 Array.copy
只是一个C风格的的memcpy
等同,这不是我要找的。 p >
您可以添加它作为一个扩展方法:
公共静态T []子数组< T>(这件T []的数据,INT指数,INT的长度)
{
T []结果=新的T [长度];
Array.Copy(数据,索引,结果,0,长度);
返回结果;
}
静态无效的主要()
{
INT []数据= {0,1,2,3,4,5,6,7,8,9};
INT []亚= data.SubArray(3,4); //包含{3,4,5,6}
}
更新再克隆(这不明显在原来的问题)。如果你的真正的希望有一个深克隆;是这样的:
公共静态T [] SubArrayDeepClone< T>(这件T []的数据,INT指数,INT的长度)
{
T [] arrCopy =新T [长度];
Array.Copy(数据,索引arrCopy,0,长度);
使用(MemoryStream的毫秒=新的MemoryStream())
{
变种BF =新的BinaryFormatter();
bf.Serialize(MS,arrCopy);
ms.Position = 0;
返回(T [])bf.Deserialize(MS);
}
}
这确实需要的对象是可序列化( [Serializable接口]
或 ISerializable的
),虽然。你可以很容易地替换任何其他串行酌情 - 的XmlSerializer
,的DataContractSerializer
,protobuf网等。
需要注意的是深克隆是棘手的无序列;尤其是, ICloneable
很难在大多数情况下,信任。
I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a loop that will do it for me but I would like to keep my code as clean as possible. Is there a method in C# that can do it for me?
Something like (pseudo code):
Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)
Array.Copy
doesn't fit my needs. I need the items in the new array to be clones. Array.copy
is just a C-Style memcpy
equivalent, it's not what I'm looking for.
You could add it as an extension method:
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}
Update re cloning (which wasn't obvious in the original question). If you really want a deep clone; something like:
public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
T[] arrCopy = new T[length];
Array.Copy(data, index, arrCopy, 0, length);
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, arrCopy);
ms.Position = 0;
return (T[])bf.Deserialize(ms);
}
}
This does require the objects to be serializable ([Serializable]
or ISerializable
), though. You could easily substitute for any other serializer as appropriate - XmlSerializer
, DataContractSerializer
, protobuf-net, etc.
Note that deep clone is tricky without serialization; in particular, ICloneable
is hard to trust in most cases.
这篇关于获得子阵列从现有阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!