简体   繁体   中英

C# memcpy equivalent for vectors (C# List<T>) (Syntactic sugar)

I'm in the process of converting an old C++ library to C#.

The C++ library heavily relies on overwriting certain elements of a std::vector<T> by using memcpy(&source[d_index],&source[s_index],count*sizeof(<T>)); (note that source and target are the same here, just different indices)

My C# port of this (by implementing ICloneable and source obviously being a List<T> where T is a reference type) is:

 for (int i = 0; i < count; i++)
    source[d_index + i] = source[s_index + i].Clone(); 

This works as supposed.

However, my question is: Is there a simpler version? I obviously can't use List.InsertRange(d_index, List.GetRange(s_index, count)) because this method inserts instead of overwrite.

I can't use List<T>.CopyTo Method (Int32, T[], Int32, Int32) either as the destination has to be an array of T[] and not the list itself.

Is there a method that does what memcpy does for this specific example? I know I could easily implement an extension method myself, I was just wondering if I missed something on MSDN.

I have run into this problem myself and i came to the same conclusion either use Clone or make a copy constructor yourself.

For the CopyTo method i forgot but doesnt it just copy the references again? Other then that you can save those into a array as you said and use AddRange(array).

How about RemoveRange, followed by Insert range? Obviously only if the ranges do not overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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