這是一個可怕的方式做到這一點,但它至少工作:
for (int i = 0; i < size; i++)
{
sum[i] = (dynamic)a[i] + (dynamic)b[i];
}
它,然而,做了很多的裝箱和拆箱的。如果你想有一個更好的版本,你可能具有過載,而不是做的更好:
public static int[] Plus(int[] a, int[] b, int size)
{
int[] sum = new int[size];
for (int i = 0; i < size; i++)
{
sum[i] = a[i] + b[i];
}
return sum;
}
public static long[] Plus(long[] a, long[] b, int size)
{
long[] sum = new long[size];
for (int i = 0; i < size; i++)
{
sum[i] = a[i] + b[i];
}
return sum;
}
你也仍然可以破解一個通用版本:
public static T[] Plus<T>(T[] a, T[] b, int size)
{
switch(Type.GetTypeCode(typeof(T)))
{
case TypeCode.Int32:
return (T[])(object)Plus((int[])(object)a, (int[])(object)b, size);
case TypeCode.Int64:
return (T[])(object)Plus((long[])(object)a, (long[])(object)b, size);
// ...etc
default:
throw new NotSupportedException();
}
}
泛型不支持'+'等運算符。有辦法做到這一點,但... – 2014-10-03 10:13:26
這可能是幫助http://stackoverflow.com/questions/9338398/how-to-sum-generic-numbers-in-c – apomene 2014-10-03 10:15:43
這可能有幫助http: //www.codeproject.com/Articles/8531/Using-generics-for-calculations – Christos 2014-10-03 10:16:21