网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 C#泛型有什么好处
内容
    关于object类型:
    1.object类型可以来引用任何类型的实例;
    2.object类型可以存储任何类型的值;
    3.可以定义object类型的参数;
    4.可以把object作为返回类型。
    但是--这样做有很大的问题
    1.会因为程序员没有记住使用的类型而出错,造成类型不兼容;
    2.值类型和引用类型的互化即装箱拆箱使系统性能下降。
    C#2.0提出的泛型就是避免强制类型转换,减少装箱拆箱提高性能,减少错误。
    System.Collections.Generic命名空间提供许多集合类和接口的泛型版本。
    定义:
    public class GenericList<T>
    {
    public void Add(T input)//T制定成类型参数
    public T Add()//T制定成返回值
    }
    <T>的T是类型参数,起占位符的作用,编译时被真正类型取代。
    使用泛型:
    GenericList<int> list1 = new GenericList<int>();
    GenericList<string> list2 = new GenericList<string>();
    GenericList<类名> list3 = new GenericList<类名>();
    GenericList<类名<int>> list4= new GenericList<类名<int>>();
    以list1为例编译器生成以下的方法:
    public void Add(int input)
    public int Add()
    有多个类型参数的泛型类:
    public class 类名<T,U>
    泛型约束:
    确保泛型类使用的参数是提供特定方法的类型。
    public class GenericList<T> where T : IEmployee
    假如IEmployee接口包含A方法,编译器会验证用于替换T的类型一定要实现IEmployee接口。
    泛型方法:允许采取定义泛型类时采用的方式
    //定义泛型方法
    static void Swap<T>(ref T lhs, ref T rhs)
    { T temp; temp = lhs; lhs = rhs; rhs = temp; }
    //使用泛型方法
    public static void TestSwap(){ int a=1,b=3;
    Swap<int>(ref a,ref b);
    string s1="Hello",s2="world";
    Swap<string>(ref s1,ref s2);}
    有泛型类,泛型接口,泛型方法,泛型委托
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/15 19:01:59