我想写一个函数,能够判断输入进来的数组类型,然后返回一个数组。
这是函数
public static IList<T> DisorderArray<T>(IList<T> array)
{
Type type = typeof(T);
byte[] keys;
switch (type.ToString())
{
case "System.Int32":
int[] arr = array as int[];
keys = new byte[arr.Length];
Array.Sort(keys, arr);
return (IList<T>)Convert.ChangeType(arr, typeof(IList<T>));
case "System.Double":
//之后都是不同类型的判断
...
default:
return default(IList<T>);
}
}
这样调用函数
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5 };
int[] newArray = (int[])DisorderArray<int>(array);
foreach(int i in newArray)
{
Console.WriteLine(i);
}
}
然后报错:
未经处理的异常: System.InvalidCastException: 对象必须实现 IConvertible。
是我对泛型的理解有问题不应该这样用,还是需要什么约束或者别的?