• .Net之美读书笔记2


    泛型的定义

    百度百科:泛型将类型参数的概念引入 .NET Framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。(也就是说类型可以当作参数在 类型声明 和类型实例化 或函数调用时传递类型)。

    • 增大了代码复用性
    • 减少了强制类型转换 提示了性能 增加了稳定性

    注意点

    泛型类型和泛型方法

    如果类型主要是对 泛型参数 的处理应声明为泛型类型,如果类型内仅仅几个方法的参数需要泛型类型建议使用泛型方法。泛型方法调用时IDE有类型推断作用,通常不用带 Type

    泛型的方法

    大多时候我们希望我需要传入的类型具有某些功能或条件,这时候我们需要用到泛型约束。当规定了泛型约束智能的IDE允许直接调用约束的能力。

    本章中的Code

    	public class Book : IComparable
    	{
    		public int Price { get; set; }
    		public string Title { get; set; }
    
    		public int CompareTo(Object other)
    		{
    			Book otherBook = other as Book;
    			return this.Price.CompareTo(otherBook.Price);
    		}
    
    		public override string ToString()
    		{
    			return string.Format("{0} Price is {1} ", this.Title, this.Price);
    		}
    	}
    
    	public class SortHelper<T> where T : IComparable
    	{
    		public void BubbleSort(T[] array)
    		{
    			int length = array.Length;
    			for (int i = 0; i <= length - 2; i++)
    			{
    				for (int j = length - 1; j > 0; j--)
    				{
    					if (array[j].CompareTo(array[j - 1]) < 0)
    					{
    						T temp = array[j];
    						array[j] = array[j - 1];
    						array[j - 1] = temp;
    					}
    				}
    			}
    		}
    	}
    
        class Program
    	{
    		static void Main(string[] args)
    		{
    			Book[] bookArray = new Book[]
    			{
    				new Book() {Price=32,Title="Learning Hard C#" },
    				new Book() {Price=30,Title="Html5" },
    				new Book() {Price=45,Title=".Net 之美" }
    			};
    
    			SortHelper<Book> sortHelper = new SortHelper<Book>();
    
    			sortHelper.BubbleSort(bookArray);
    
    			foreach(Book book in bookArray)
    			{
    				Console.WriteLine(book.ToString());
    			}
    
    			Console.ReadKey();
    
    		}
    	}
    
  • 相关阅读:
    [转]IDEA 新建 JSP 项目时
    [转] AForge.NET 图像处理类
    [转] 端口被占用的处理
    [极客大挑战 2019]PHP
    今天鸽了
    [ZJCTF 2019]NiZhuanSiWei
    [极客大挑战 2019]Secret File
    [SUCTF 2019]Pythonginx
    [CISCN2019 华北赛区 Day1 Web2]ikun
    [极客大挑战 2019]EasySQL
  • 原文地址:https://www.cnblogs.com/LoveTomato/p/8022630.html
Copyright © 2020-2023  润新知