前进中的蜗牛

番茄大叔

水滴穿石,非一日之功;没有量变,何来质变。

.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();

		}
	}
posted @ 2017-12-11 13:22  LoveTomato  阅读(133)  评论(0编辑  收藏  举报