ArraySegment<T>有什么用?班级? [英] What is the use of the ArraySegment&lt;T&gt; class?

查看:34
本文介绍了ArraySegment<T>有什么用?班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在继承 MessageEncoder 类时遇到了 ArraySegment 类型.

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

我现在明白它是给定数组的一部分,需要一个偏移量,不可枚举,并且没有索引器,但我仍然无法理解它的用法.有人可以举例解释一下吗?

I now understand that it's a segment of a given array, takes an offset, is not enumerable, and does not have an indexer, but I still fail to understand its usage. Can someone please explain with an example?

推荐答案

ArraySegment.NET 4.5+ 和 .NET Core 现在实现:

ArraySegment<T> has become a lot more useful in .NET 4.5+ and .NET Core as it now implements:

  • IList
  • ICollection
  • IEnumerable
  • IEnumerable
  • IReadOnlyList
  • IReadOnlyCollection

相对于 .NET 4 版本 没有实现任何接口.

as opposed to the .NET 4 version which implemented no interfaces whatsoever.

班级现在可以参与到 LINQ 的奇妙世界中,因此我们可以执行 LINQ 常见的事情,例如查询内容、在不影响原始数组的情况下反转内容、获取第一项等:

The class is now able to take part in the wonderful world of LINQ so we can do the usual LINQ things like query the contents, reverse the contents without affecting the original array, get the first item, and so on:

var array = new byte[] { 5, 8, 9, 20, 70, 44, 2, 4 };
array.Dump();
var segment = new ArraySegment<byte>(array, 2, 3);
segment.Dump(); // output: 9, 20, 70
segment.Reverse().Dump(); // output 70, 20, 9
segment.Any(s => s == 99).Dump(); // output false
segment.First().Dump(); // output 9
array.Dump(); // no change

这篇关于ArraySegment<T>有什么用?班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆