• 第2章 C#中的泛型


    2.1 理解泛型
    2.1.1 为什么要有泛型

    并不一定要使用字符T作为类型参数的名称,也可以使用其他的字符,但习惯上使用T。

    2.1.2 类型参数约束
    什么是“向下的强制转换(downcast)”?因为Object是所有类型的基类,Book类继承自Object类,在这个金字塔状的继承体系中,Object位于上层,Book位于下层,所以将Object转换为Book称作“向下的强制转换”。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Text.RegularExpressions;
    
    namespace _.net之美
    {
        class Program
        {
            static void Main(string[] args)
            {
                Book[] books=new Book[2];
                Book book1 = new Book(10, "book1");
                Book book2 = new Book(20, "book2");
                books[0] = book1;
                books[1] = book2;
                SortHelper<Book> sortHelper = new SortHelper<Book>();
                sortHelper.BubbleSort(books);
                foreach (Book book in books)
                {
                    Console.WriteLine("{0},{1}", book.Price, book.Title);
                }
                Console.Read();
            }
        }
    
        public class SortHelper<T> where T : IComparable
        {
            public void BubbleSort(T[] array)
            {
                int length = array.Length;
                for (int i = 0; i < length-1; i++)
                {
                    for (int j = 0; j < length - 1 - j; j++)
                    {
                        if (array[j].CompareTo(array[j + 1]) > 0)
                        {
                            T tmp = array[j];
                            array[j] = array[j + 1];
                            array[j + 1] = tmp;
                        }
                    }
                }
            }
        }
    
        public class Book:IComparable
        {
            decimal price;
            string title;
            public Book() { }
            public Book(decimal price, string title)
            {
                this.price = price;
                this.title = title;
            }
            public decimal Price
            {
                get { return this.price; }
            }
    
            public string Title
            {
                get { return this.title; }
            }
    
            public int CompareTo(object obj)
            {
                Book book = (Book)obj;
                return this.Price.CompareTo(book.Price);
            }
        }
    }
    View Code

    2.2 泛型与集合类型
    2.2.1 避免隐式的装箱和拆箱
    使用List<T>比使用ArrayList提高了差不多3倍性能。当使用一个大的值类型时,比如枚举或者结构,获得的差异还会更大。(P25)

    2.2.2 编译时的类型安全
    2.2.3 使用泛型的一个小技巧

  • 相关阅读:
    js学习(4) 函数
    Js学习(3) 数组
    NGUI的UILabel
    unity模型部分替换
    工作流程
    unity 资源内存管理
    unity 跑酷demo
    unity动画相关
    unity之C#回调函数
    maya导入unity
  • 原文地址:https://www.cnblogs.com/liuslayer/p/5322294.html
Copyright © 2020-2023  润新知