泛型编程:
问题提出:
面向对象编程存在一个众所周知的问题:“代码膨胀”,对于方法或方法集合,为了说明其所有可能的返回类型需要进行多次冗余性编写,例如:对于一个值交换函数,函数处理值可能为字符型,也可能为整数型,或是浮点型,那么为满足不同功能需要不断重写相同功能代码,为解决此问题,我们提出了泛型编程。
解决方法:
泛型类型提供占位符<>,在括号内填充特定的数值类型完成函数计算,具体示例如下:
static void swap<T>(ref T var1, ref T var2)
{
T TEMP;
TEMP = var1;
var1 = var2;
var2 = TEMP;
}
static void Main(string[] args)
{
int num1 = 9;
int num2 = 25;
Console.WriteLine("交换前: num1:" + num1.ToString() + " num2:" + num2.ToString());
swap<int>(ref num1,ref num2);
Console.WriteLine(" num1:" + num1.ToString() + " num2:" + num2.ToString());
string str1 = "GAO";
string str2 = "XIANG";
Console.WriteLine("交换前: str1:" + str1 + " str2:" + str2);
swap<string>(ref str1, ref str2);
Console.WriteLine(" str1:" + str1 + " str2:" + str2);
Console.ReadLine();
}
程序结果:
时间测试:
{
TimeSpan duration;
public TimeTest()
{
duration = new TimeSpan(0);
}
public void start()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
public void stop()
{
duration = Process.GetCurrentProcess().TotalProcessorTime;
}
public TimeSpan result()
{
return duration;
}
}
{
for (int i = 0; i < num.GetUpperBound(0); i++)
{
Console.Write(num[i] + " ");
}
}
private static void Builearray(int[] num)
{
for (int i = 0; i < num.GetUpperBound(0); i++)
{
num[i++] = i * i;
}
}