C#泛型

泛型

可空类型:通常值类型必须初始化之后才能使用,使用System.Nullable<T>类型使得值类型可空(为NULL),如System.Nullable<int>,可以简写为int?

??运算符:即空接合运算符,是一个二元运算符,允许给可能等于null的表达式提供另一个值

例子:op1??op2等价于op1=null?op1:op2

泛型:

泛型集合List<T>

创建代码:List<T> syCollection=new List<T>();

常用成员:

int Count:给出集合中项的个数

void Add(T item):添加一个项到集合中

void AddRange(Ienumerable<T>):添加多个项

int Capacity:获取或设置集合可包含项数

void Clear():删除所有项

Bool Contains(T item):是否包含item

int IndexOf(T item):获取item的索引,没有则返回-1

void Insert(int index,T item):将item插入index处

bool Remove(T item):删除第一个item

void Remove(int index):从集合中删除index处的项

 

泛型可认为是一种框架模板,泛型集合把应用这种框架的实例类集合到一起,泛型有泛型类、泛型接口、泛型委托、泛型方法

 

泛型排序与搜索、default关键字、约束(以后整)

Dictionary<K,V>定义健/值的集合,健值必须唯一

 

::运算符指定命名空间

 

泛型例子:

    //泛型应用 
    public class Person<T>//创建泛型类
        {
            private T temp;
            public Person(T nameAge)
            {
                this.temp = nameAge;
            }
            public void Read()
            {
                Console.WriteLine(temp);
            }
        }
        static void Main(string[] args) {
            Person<string> personName = new Person<string>("jack");
        //string类型名字
            Person<int> personAge = new Person<int>(15);
        //int类型名字
            personName.Read();//输出jack
            personAge.Read();//输出15
            for (;;) ;
        }

泛型类集合

//泛型类集合 
public class Person
        {
            private string name;
            public  Person(string oneName)//构造函数
            {
                name = oneName;
            }
            public void SayHello(){
                Console.WriteLine("Hello" + name);
            }
        }
        static void Main(string[] args) {
        List<Person> colPerson = new List<Person>();
    //创建集合类
         colPerson.Add(new Person("jack"));
         colPerson.Add(new Person(“jhon”));//添加集合类
            foreach (Person aPerson in colPerson)
                aPerson.SayHello();//输出Hellojack  Hellojhon
        Person smith = new Person("smith");
            colPerson.Add(smith);
            Console.WriteLine(colPerson.Contains(smith));//输出true
            for (;;) ;
        }

 

posted @ 2016-03-07 20:16  大尾巴贝贝  阅读(348)  评论(0编辑  收藏  举报