简体   繁体   English

浅拷贝值类型数组的一段

[英]shallow-copy a segment of a value type array

I'm trying to shallow-copy a double[] into segments, and pass those segments to new threads, like so: 我试图将double []浅复制到段中,然后将这些段传递给新线程,如下所示:

for (int i = 0; i < threadsArray.Length; i++)
{
    sub[i] = new double[4];

    //Doesn't shallow copy since double is a value type
    Array.Copy(full, i * 4, sub[i], 0, 4);
    double[] tempSub = sub[i];

    threadsArray[i] = new Thread(() => DoStuff(tempSub));
    threadsArray[i].Start();               
}

What would be the best way to have the created segments reference the original array? 使创建的段引用原始数组的最佳方法是什么?

You could use the ArraySegment<T> structure: 您可以使用ArraySegment<T>结构:

for (int i = 0; i < threadsArray.Length; i++)
{
    sub[i] = new ArraySegment<double>(full, i * 4, 4);

    ArraySegment<double> tempSub = sub[i];

    threadsArray[i] = new Thread(() => DoStuff(tempSub));
    threadsArray[i].Start(); 
}

(note that you will need to change the signature of DoStuff to accept an ArraySegment<double> (or at least an IList<double> instead of an array) (请注意,您将需要更改DoStuff的签名以接受ArraySegment<double> (或至少是IList<double>而不是数组))

ArraySegment<T> doesn't copy the data; ArraySegment<T>不复制数据。 it just represents an segment of the array, by keeping a reference to the original array, an offset and a count. 它通过保留对原始数组的引用,偏移量和计数来仅表示数组的一部分。 Since .NET 4.5 it implements IList<T> , which means you can use it without worrying about manipulating the offset and count. 从.NET 4.5开始,它实现了IList<T> ,这意味着您可以使用它而不必担心操纵偏移量和计数。

In pre-.NET 4.5, you can create an extension method to allow easy enumeration of the ArraySegment<T> : 在.NET 4.5之前的版本中,您可以创建扩展方法以允许轻松枚举ArraySegment<T>

public static IEnumerable<T> AsEnumerable<T>(this ArraySegment<T> segment)
{
    for (int i = 0; i < segment.Count; i++)
    {
        yield return segment.Array[segment.Offset + i];
    }
}

...

ArraySegment<double> segment = ...
foreach (double d in segment.AsEnumerable())
{
    ...
}

If you need to access the items by index, you will need to create a wrapper that implements IList<T> . 如果需要按索引访问项目,则需要创建一个实现IList<T>的包装器。 Here's a simple implementation: http://pastebin.com/cRcpBemQ 这是一个简单的实现: http : //pastebin.com/cRcpBemQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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