泛型方法

using System;
using System.Collections.Generic;
using System.Text;

namespace 泛型方法
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = Finder.Find<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 6);
            //int i = Finder.Find<string>(new string[] { "1", "2", "3", "4", "5", "6", "7", "8" }, "6");
            Console.WriteLine("6在数组中的位置:" + i.ToString());
            Console.ReadLine();
        }
    }

    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))//用Equals比较两个对象的值
                {
                    return i;//如果存在于对象数组中,返回数组中的位置
                }
            }
            return -1;//如果不存在,则返回-1
        }
    }
}

 

posted @ 2013-09-17 23:33  cppwen  阅读(210)  评论(0编辑  收藏  举报