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
The type arguments for method 'GenericArrayFunction(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Judging from your particular example, could you not define two methods and let the compiler choose the correct one when an array is passed in?
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
}
}
Just because T
is an array type doesn't mean that it's also an array of T
. In fact, the only way that could happen would be for T
to be something like object
, Array
or one of the interfaces implemented by arrays.
What are you really trying to do? I suspect you want to find out the element type of the array, and then call GenericArrayFunction
with the appropriate T
- but that won't be the same T
, and you'll need to call it with reflection, which will be somewhat painful. (Not too bad, but unpleasant.)
I suspect you don't fully understand C#/.NET generics - please give us more context about the bigger picture so we can help you better.
EDIT: The reflection approach would be something like this:
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 });
}
...
}
Note that this will still fail for rectangular arrays, which get even harder to cope with.
It is not possible. T
can never be T[]
. T
is always certain type, not just placeholder. If T
is array (int[]
) then T[]
will be int[][]
.
Edit: There are some exceptions (like object
is object[]
), but in general case (and thats what generics are) T can't be T[]
精彩评论