using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 泛型比较大小 { class Program { //Compare<T>是泛型类,T为类型参数 public class Compare<T> where T : IComparable { //使用泛型实现的比较方法 public static T compareGeneric(T t1, T t2) { if (t1.CompareTo(t2) > 0) { return t1; } else { return t2; } } } static void Main(string[] args) { //调用泛型方法 Console.WriteLine(Compare<int>.compareGeneric(1, 2)); Console.WriteLine(Compare<string>.compareGeneric("aa", "a")); Console.ReadKey(); } } }
时间: 2024-10-20 08:35:43