如果它是数组,我想将 T 转换为 T[]。
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]);
}
}
...
}
错误 如果我尝试 (T[])t
Cannot convert type 'T' to 'T[]'
错误 如果我只是尝试通过 t
The type arguments for method 'GenericArrayFunction(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.
最佳答案
从你的具体例子来看,你能不能定义两个方法,让编译器在传入数组时选择正确的方法?
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
}
}
关于C#:将 T 转换为 T[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3653209/