What is the use of the ArraySegment class?

后端 未结 6 2067
离开以前
离开以前 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 14:56

    In simple words: it keeps reference to an array, allowing you to have multiple references to a single array variable, each one with a different range.

    In fact it helps you to use and pass sections of an array in a more structured way, instead of having multiple variables, for holding start index and length. Also it provides collection interfaces to work more easily with array sections.

    For example the following two code examples do the same thing, one with ArraySegment and one without:

            byte[] arr1 = new byte[] { 1, 2, 3, 4, 5, 6 };
            ArraySegment seg1 = new ArraySegment(arr1, 2, 2);
            MessageBox.Show((seg1 as IList)[0].ToString());
    

    and,

            byte[] arr1 = new byte[] { 1, 2, 3, 4, 5, 6 };
            int offset = 2;
            int length = 2;
            byte[] arr2 = arr1;
            MessageBox.Show(arr2[offset + 0].ToString());
    

    Obviously first code snippet is more preferred, specially when you want to pass array segments to a function.

提交回复
热议问题