泛型方法
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(); } } }
相关文章推荐
- C++中的volatile
- iOS应用安全开发总结
- TinyOS05:Avrora的安装及简介
- iOS -- 6位密码验证
- IOS中货币高精度要求使用NSDecialNumber、
- Myeclipse 10 Maven 构建 Java Web 项目
- Oracle建表,建序列,建触发器,自动生成唯一主键。dual解释
- MySQL操作笔记(2)
- PHP编程开发怎么提高编程效率 提高PHP编程技术
- vim# set
- eclipse.ini内存设置(转)
- 在树莓派上安装MySQL数据库和简单使用方法
- 从单线程到多线程之线程控制
- Super关键字
- Python基础之【第一篇】
- 类似与三元表达式的 json 读取值
- Spark中稀疏矩阵的存储方式
- Vi技巧小结
- MyBatis动态参数排序的注意事项
- ContentProvider学习笔记