static void GetSum
{
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(a);
//本来是想返回T类型的 结果一直无法实现
static void Main(string[] args)
{
Console.WriteLine(sum(1, 2));
Console.ReadLine();
}
public static T sum(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());
}
}
}
static T Sum(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();
}
dynamic动态类型