C# 使用自定义的泛型函数/方法对泛型数组进行四则运算
static void GetSum<T>(T[] a)
{
if (a == null)
{
Console.WriteLine("无意义");
return;
}
if (a is int[])
{
int sum = 0;
for (int i = 0; i < a.Length; i++)
{
sum += Convert.ToInt32(a[i]);
}
Console.WriteLine(sum);
}
else if (a is double[])
{
double sum = 0;
for (int i = 0; i < a.Length; i++)
{
sum += Convert.ToDouble(a[i]);
}
Console.WriteLine(sum);
}
else if (a is float[])
{
float sum = 0;
for (int i = 0; i < a.Length; i++)
{
sum += Convert.ToSingle(a[i]);
}
Console.WriteLine(sum);
}
}
//使用时:
int[] a ={ 1, 2, 3, 4 };
GetSum<int>(a);
//本来是想返回T类型的 结果一直无法实现
static void Main(string[] args)
{
Console.WriteLine(sum<int>(1, 2));
Console.ReadLine();
}
public static T sum<T>(T a, T b) where T : struct
{
string ts = typeof(T).ToString();
switch (ts.Substring(ts.LastIndexOf(".") + 1))
{
case "Int32"://示例,只写了整数
{
int sum = Convert.ToInt32(a) + Convert.ToInt32(b);
return (T)Convert.ChangeType(sum, typeof(T));
}
default://只是为了防止编译错误
{
return (T)(new object());
}
}
}
2018-01-17
static T Sum<T>(params T[] arrays) where T : struct
{
if (arrays.Length > 0)
{
dynamic sum = default(T);
foreach (T memb in arrays)
sum += memb;
return sum;
}
else
throw new System.IndexOutOfRangeException();
}