现在的位置: 首页 > 综合 > 正文

泛型学习笔记

2012年06月24日 ⁄ 综合 ⁄ 共 1973字 ⁄ 字号 评论关闭

泛型是.NEt framwork 2.0里面提出来的,他很好的解决了我们在项目是性能上的问题,使用它可以很好的提高我们项目中效率,性能等
现在说说泛型的好处:
1.代码重用性提高,安全性得到更好的保证;
2.主要用在集合中;
3.自己可以创建泛型类,方法,接口,委托等

请看如下的一个简单示例:

新建一个User的泛型类:

#region
//======================================================================
//
//        Copyright (C) CIM西安研发中心    
//        All rights reserved
//
//        类名 :Console_B.Show
//        模块描述 :
//
//        创建人: 曹代明 
//          创建时间:    05/07/2008 11:02:49
//
//          修改人:
//          修改时间:
//        个人网站:http://caodaiming.cnblogs.com
//
//======================================================================
#endregion
using System;
using System.Collections.Generic;
using System.Text;

namespace Console_B
{
   
public class Show<T>
    {
       
public void aa(T b)
       {
           Console.WriteLine(b.ToString()
+"----"+b.GetType().ToString());
       }

      
   }
}

把这个Show类加上了<T>这样就成泛型了,下面这个aa(T b)方法,他的类型可以是认意的哟,这样是不是可以提高了代码的重用,
下来看看是怎么来调用的吧?

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

namespace Console_B
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Show
<int> show = new Show<int>();
            show.aa(
22);
            Show
<string> show2 = new Show<string>();
            show2.aa(
"caodaiming");
        }

        
    }
}

上面不是提到了,代码的重用吗?这里主是一个很好的说明,如果你要用到aa()方法,你就可以传入任何的数据类型,这是一个很方便的事,很
简单吧

下面看看List的泛型号吧

List<string> list = new List<string>();
            list.Add(
"a");
            list.Add(
"c");
            list.Add(
"f");
            list.Add(
"b");
            list.Sort();
            
foreach (string l in list)
            {
                Console.WriteLine(l.ToString());
            }

            List<int> list2 = new List<int>();
            list2.Add(
1);
            list2.Add(
4);
            list2.Add(
2);
            list2.Add(
5);
            list2.Add(
6);
            list2.Add(
9);
            list2.Sort();
            
foreach (int l in list2)
            {
                Console.WriteLine(l.ToString());
            }

这里在你泛型号时是什么类型,那么在添加时就要添加什么样的数据类型如:List<string>添加是就应该是string类型的数据;

抱歉!评论已关闭.