作者:2702934635_941 | 来源:互联网 | 2022-11-20 17:55
正在研究跨度,记忆等.我试图理解从Span中获取int的预期方法
在我读过的所有博客文章中都暗示了一种NonPortableCast
方法正在实施,但它似乎已被删除.
我也读过有关它可能在.Cast
Marc Gravell的一个帖子上重命名但又一次,我无法在任何地方找到它.
所以给出:
public ReadOnlySpan MessageBytes {get;set;}
public ReadOnlySpan ItemLengthBytes => MessageBytes.Slice(0,4);
如何将这4个字节转换为int?
这就是我现在正在做的,这是正确的方法吗?或者有更快的方法吗?
public int ItemLength => Convert.ToInt32(ItemLengthBytes.ToArray());
Jeff Dammeye..
8
在最近的位中,该Cast
方法现在正System.Runtime.InteropServices.MemoryMarshal
如下所示:https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.cast?view = netcore-2.2# System_Runtime_InteropServices_MemoryMarshal_Cast__2_System_ReadOnlySpan___0__
但是如果你打算读出一个int,你可能想要在同一类型上使用'Read'方法:https:
//docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.读?视图=磊-2.2
因此:
public int ItemLength => MemoryMarshal.Read(ItemLengthBytes);
你写的内容也会起作用,但它会失去Span的很多性能优势,因为你每次使用时都会做额外的内存复制和堆分配ToArray()
.
1> Jeff Dammeye..:
在最近的位中,该Cast
方法现在正System.Runtime.InteropServices.MemoryMarshal
如下所示:https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.cast?view = netcore-2.2# System_Runtime_InteropServices_MemoryMarshal_Cast__2_System_ReadOnlySpan___0__
但是如果你打算读出一个int,你可能想要在同一类型上使用'Read'方法:https:
//docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.读?视图=磊-2.2
因此:
public int ItemLength => MemoryMarshal.Read(ItemLengthBytes);
你写的内容也会起作用,但它会失去Span的很多性能优势,因为你每次使用时都会做额外的内存复制和堆分配ToArray()
.