您的位置:首页 > 其它

泛型方法

2015-11-09 11:30 183 查看

在非泛型类中使用泛型方法

SortHelper.cs(非泛型类)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort
{
class SortHelper    //定义实现冒泡排序算法的类
{
public void BubbleSort<T>(T[] array)where T :IComparable
{
//where T :IComparable是为了使用Icomparable接口的CompareTo方法比较大小
int length = array.Length;
for(int i=0;i<=length-2;i++)
{
for(int j=length-1;j>=1;j--)
{
if(array[j].CompareTo(array[j-1])<0)
{
//如果前面的元素较大,交互相邻两个元素
T temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
}
}


Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
SortHelper sorter = new SortHelper();
int[] array = { 8, 2, 4, 6 };
sorter.BubbleSort<int>(array);//此时指明了参数类型为int型
foreach(int i in array)
{
Console.Write("{0} ", i);
}
Console.Read();
}
}
}

泛型类中的泛型方法

SortHelper.cs(泛型类)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort
{
class SortHelper<T> where T : IComparable
{
public void BubbleSort(T[] array)
{
//where T :IComparable是为了使用Icomparable接口的CompareTo方法比较大小
int length = array.Length;
for(int i=0;i<=length-2;i++)
{
for(int j=length-1;j>=1;j--)
{
if(array[j].CompareTo(array[j-1])<0)
{
//如果前面的元素较大,交互相邻两个元素
T temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
}
}


Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
SortHelper<int> sorter = new SortHelper<int>();
int[] array = { 8, 2, 4, 6 };
sorter.BubbleSort(array);  //此时确定类型为int型
foreach(int i in array)
{
Console.Write("{0} ", i);
}
Console.Read();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: