zoukankan      html  css  js  c++  java
  • .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();
    
    		}
    	}
    
  • 相关阅读:
    Roads in the Kingdom CodeForces
    Vasya and Shifts CodeForces
    SOS dp
    Singer House CodeForces
    Codeforces Round #419 (Div. 1) (ABCD)
    在踏踏实实的生活里让自己坚持去做梦
    Replace Delegation with Inheritance
    Replace Inheritance with Delegation
    Replace Parameter with Methods
    Preserve Whole Object
  • 原文地址:https://www.cnblogs.com/LoveTomato/p/8022630.html
Copyright © 2011-2022 走看看