C# - 返回通用数组类型

Arj*_*Arj 3 c# arrays generics types generic-programming

如果我有一个简单的Utility函数将数组复制到一个新数组:

public static object[] CopyTo(object[] original, int startIndex, int endIndex)
{
    List<object> copied - new List<object>();
    for (int i = startIndex; i <= endIndex; i++) 
    {
        copied.Add(original[i]);
    }
    return copied.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

然后我希望能够像这样调用它:

int[] newThing = CopyTo(new int[] { 10, 9, 8, 7, 6 }, 2, 4);
Run Code Online (Sandbox Code Playgroud)

编译错误说cannot convert from int[] to object[].这是预期的,因为我的CopyTo函数特别想要一个对象数组,而不是一个整数数组.

如何更改CopyTo的声明以使其动态接受并返回任何类型的数组? 我相信泛型是这样的(尽管我对此并不太熟悉)所以我尝试过:

public static T[] CopyTo(T[] original, int startIndex......)
Run Code Online (Sandbox Code Playgroud)

但编译器不会将T识别为类型.

Abb*_*bas 7

要使其通用,请使用以下代码:

public static T[] CopyTo<T>(T[] original, int startIndex, int endIndex)
{
    List<T> copied = new List<T>();
    for (int i = startIndex; i <= endIndex; i++) 
    {
        copied.Add(original[i]);
    }
    return copied.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

只需提一下,您也可以在不创建List<T>并将列表作为数组返回的情况下执行此操作.只需创建一个数组(长度等于所需元素的数量)并填充它:

public static T[] CopyTo<T>(T[] original, int startIndex, int endIndex)
{
    int count = (endIndex - startIndex) + 1;
    int index = 0;
    T[] copied = new T[count];

    for (int i = startIndex; i <= endIndex; i++) 
        copied[index++] = original[i];

    return copied;
}
Run Code Online (Sandbox Code Playgroud)

您还可以为它创建一个扩展方法:

public static class Extensions
{
    public static T[] CopyTo<T>(this T[] source, int start, int end)
    {
        int count = (end - start) + 1;
        int index = 0;
        T[] copied = new T[count];

        for (int i = start; i <= end; i++) 
            copied[index++] = source[i];

        return copied;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样称呼:

var original = new int[] { 10, 9, 8, 7, 6 };
var newThing = original.CopyTo(0, 2);
Run Code Online (Sandbox Code Playgroud)

或者对于一个字符串数组:

var strOrig = "one.two.three.four.five.six.seven".Split('.');
var strNew = strOrig.CopyTo(2, 5);
Run Code Online (Sandbox Code Playgroud)