What is the use of the ArraySegment class?

后端 未结 6 2066
离开以前
离开以前 2020-11-27 14:44

I just came across the ArraySegment type while subclassing the MessageEncoder class.

I now understand that it\'s a segment of a

6条回答
  •  攒了一身酷
    2020-11-27 15:11

    It is a puny little soldier struct that does nothing but keep a reference to an array and stores an index range. A little dangerous, beware that it does not make a copy of the array data and does not in any way make the array immutable or express the need for immutability. The more typical programming pattern is to just keep or pass the array and a length variable or parameter, like it is done in the .NET BeginRead() methods, String.SubString(), Encoding.GetString(), etc, etc.

    It does not get much use inside the .NET Framework, except for what seems like one particular Microsoft programmer that worked on web sockets and WCF liking it. Which is probably the proper guidance, if you like it then use it. It did do a peek-a-boo in .NET 4.6, the added MemoryStream.TryGetBuffer() method uses it. Preferred over having two out arguments I assume.

    In general, the more universal notion of slices is high on the wishlist of principal .NET engineers like Mads Torgersen and Stephen Toub. The latter kicked off the array[:] syntax proposal a while ago, you can see what they've been thinking about in this Roslyn page. I'd assume that getting CLR support is what this ultimately hinges on. This is actively being thought about for C# version 7 afaik, keep your eye on System.Slices.

    Update: dead link, this shipped in version 7.2 as Span.

    Update2: more support in C# version 8.0 with Range and Index types and a Slice() method.

提交回复
热议问题