溫馨提示×

C#中實現自定義類型的Slice方法

c#
小樊
115
2024-07-21 00:44:58
欄目: 編程語言

在C#中實現自定義類型的Slice方法可以通過擴展方法來實現。以下是一個示例代碼:

using System;

public static class CustomTypeExtensions
{
    public static T[] Slice<T>(this T[] array, int start, int end)
    {
        if (start < 0 || end < 0 || start >= array.Length || end > array.Length || start > end)
        {
            throw new ArgumentException("Invalid start or end index");
        }

        int length = end - start;
        T[] result = new T[length];
        Array.Copy(array, start, result, 0, length);

        return result;
    }
}

public class Program
{
    public static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int[] slicedNumbers = numbers.Slice(2, 5);

        foreach (int number in slicedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

在上面的示例中,我們定義了一個擴展方法Slice,它接受一個起始索引和一個結束索引,并返回一個切片后的數組。在Main方法中,我們使用Slice方法對一個整數數組進行切片操作,并打印出切片后的結果。

通過這種方式,我們可以方便地在自定義類型上實現切片方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女