C #: convert T to T []

I would like to convert T to T [] if it is an array.

static T GenericFunction<T>(T t)
{
       if (t == null) return default(T);

       if (t.GetType().IsArray)
       {
            //if object is an array it should be handled
            //by an array method
            return (T) GenericArrayFunction((T[])t); 
       }
       ...
}

static T[] GenericArrayFunction<T>(T[] t)
{
       if (t == null) return default(T);

       for (int i = 0 ; i < t.Length ; i++) 
       {
            //for each element in array carry
            //out Generic Function
            if (t[i].GetType().IsArray())
            {
                 newList[i] = GenericArrayFunction((T[])t[i]); 
            }
            else
            {
                 newList[i] = GenericFunction(t[i]);
            }
       }
       ...
}

Error If I try (T []) t

Cannot convert type 'T' to 'T []'

Error If I just try to pass t

Type arguments for the 'GenericArrayFunction (T [])' method cannot be taken out of use. Try explicitly specifying type arguments.

+3
source share
3 answers

, T - , , T. , , , , T - object, Array , .

? , , GenericArrayFunction T - T, , . ( , .)

, #/.NET generics - , , .

EDIT: :

private static readonly ArrayMethod = typeof(NameOfContainingType)
    .GetMethod("GenericArrayFunction", BindingFlags.Static | BindingFlags.NonPublic);

...

static T GenericFunction<T>(T t)
{
       if (t == null) return default(T);

       if (t is Array)
       {
           Type elementType = t.GetType().GetElementType();
           MethodInfo method = ArrayMethod.MakeGenericMethod(new[] elementType);
           return (T) method.Invoke(null, new object[] { t });
       }
       ...
}

, , .

+2

, , ?

using System;

class Program
{
    static T GenericFunction<T>(T t)
    {
        Console.WriteLine("GenericFunction<T>(T)");
        return default(T);
    }

    static T[] GenericFunction<T>(T[] t)
    {
        // Call the non-array function
        for(int i = 0; i < t.Length; ++i)
            t[i] = GenericFunction(t[i]);

        Console.WriteLine("GenericFunction<T>(T[])");
        return new T[4];
    }

    static void Main()
    {
        int[] arr = {1,2,3};
        int i = 42;

        GenericFunction(i);   // Calls non-array version
        GenericFunction(arr); // Calls array version
    }
}
+4

It's impossible. Tcan never be T[]. T- It is always a certain type, not just a placeholder. If T- an array ( int[]), then it T[]will be int[][].

Change . There are some exceptions (for example, objectis object[]), but in the general case (and this is what the generic elements are) T cannot be T []

+2
source

Source: https://habr.com/ru/post/1763491/


All Articles