How can I get a Span from a List while avoiding needless copies?

后端 未结 3 1557
天涯浪人
天涯浪人 2021-02-04 01:29

I have a List containing some data. I would like to pass it to a function which accepts ReadOnlySpan.

List i         


        
3条回答
  •  走了就别回头了
    2021-02-04 01:48

    In .Net 5.0, you can use CollectionsMarshal.AsSpan() (source, GitHub isue) to get the underlying array of a List as a Span.

    Keep in mind that this is still unsafe: if the List reallocates the array, the Span previously returned by CollectionsMarshal.AsSpan won't reflect any further changes to the List. (Which is why the method is hidden in the System.Runtime.InteropServices.CollectionsMarshal class.)

提交回复
热议问题