基于C#通过泛型方法查找数组元素例子是小编为大家整理的一个C#定义一个泛型方法,能够用来查找指定值在数组中的索引,从而查找数组中指定的元素,具体请参见代码注释,有兴趣的编程爱好者不要错过了,一块来详细了解下吧:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ArrayInfo { public partial class Frm_Main : Form { public Frm_Main() { InitializeComponent(); } public class Finder { // 定义一个泛型方法,用来查找指定值在数组中的索引 public static int Find<T>(T[] items, T item) { for (int i = 0; i < items.Length; i++)//遍历泛型数组 { if (items[i].Equals(item))//判断是否找到了指定值 { return i;//返回指定值在数组中的索引 } } return -1;//要是没有找到,返回-1 } } private void button1_Click(object sender, EventArgs e) { string[] Str = new string[] { "C#", "JAVA", "ASP.NET", "PHP", "VB", "VC", "JS", "PB", "F#" };//声明一个字符串类型的数组 MessageBox.Show(Finder.Find<string>(Str, "PHP").ToString());//查找字符串“PHP”在数组中的索引 } private void button2_Click(object sender, EventArgs e) { int[] IntArray = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };//声明一个整数类型的数组 MessageBox.Show(Finder.Find<int>(IntArray, 60).ToString());//查找数字60在数组中的索引 } private void button3_Click(object sender, EventArgs e) { bool[] IntArray = new bool[] { true, false};//声明一个布尔类型的数组 MessageBox.Show(Finder.Find<bool>(IntArray, false).ToString());//查找false在数组中的索引 } } }