实现原理代码如下(对算法稍有了解都会明白原理的:)): using System;using System.Collections.Generic;using System.Collections;using System.Text; namespace DataStructureConsoleApplication{ class GenericProgram { //exchange the variables using the generic static void Swap<T>(ref T val1, ref T val2) { T temp; temp = val1; val1 = val2; val2 = temp; } static void Main(string[] args) { //assign the integer variables using the generic int num1 = 100; int num2 = 200; Console.WriteLine("num1={0}",num1); Console.WriteLine("num2={0}",num2); Swap<int>(ref num1,ref num2); Console.WriteLine("num1={0}", num1); Console.WriteLine("num2={0}", num2); //assign the string variables using the generic string str1 = "goal"; string str2 = "bell"; Console.WriteLine("str1={0}" , str1); Console.WriteLine("str2={0}" ,str2); Swap<string>(ref str1,ref str2); Console.WriteLine("str1={0}", str1); Console.WriteLine("str2={0}", str2); } }} 运行结果: num1=100 num2=200 num1=200 num2=100 str1=goal str2=bell str1=bell str2=goal

评论