Program.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleGenericMethod
  7. {
  8. public class Finder //建立一个公共类Finder
  9. {
  10. public static int Find<T>(T[] items, T item) //创建泛型方法
  11. {
  12. for (int i = 0; i < items.Length; i++) //调用for循环
  13. {
  14. if (items[i].Equals(item)) //调用Equals方法比较两个数
  15. {
  16. return i; //返回相等数在数组中的位置
  17. }
  18. }
  19. return -1; //如果不存在指定的数,则返回-1
  20. }
  21. }
  22. internal class Program
  23. {
  24. static void Main(string[] args)
  25. {
  26. int i = Finder.Find<int>(new int[] { 1, 2, 3, 4, 5, 6, 8, 9 }, 6); //调用泛型方法,并定义数组指定数字
  27. Console.WriteLine("6在数组中的位置:" + i.ToString()); //输出中数字在数组中的位置
  28. Console.ReadLine();
  29. }
  30. }
  31. }