泛型中的指定类型查找实例

泛型用起来确实方便,如下程序将在ArrayList中寻找指定的类型

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

namespace LINQ查询操作
{
    class Program
    {
        static void Main(string[] args)
        {
            寻找指定类型<bool>();
            寻找指定类型<int>();
            寻找指定类型<string>();
            Console.ReadLine();

        }

        private static void 寻找指定类型<T>()
        {
            ArrayList randomList = new ArrayList();
            randomList.Add(1);
            randomList.Add(2);
            randomList.Add(3);
            randomList.Add(4);
            randomList.Add(5);
            randomList.Add("one");
            randomList.Add("two");
            randomList.Add("three");
            randomList.Add("four");
            randomList.Add("five");
            randomList.Add(true);
            randomList.Add(false);
            randomList.Add(true);

            var query = randomList.OfType<T>();
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

结果如下:

image

posted @ 2011-04-19 14:25  爱玩的安哥  阅读(419)  评论(0编辑  收藏  举报