C#,ch5泛型.ppt_第1頁
C#,ch5泛型.ppt_第2頁
C#,ch5泛型.ppt_第3頁
C#,ch5泛型.ppt_第4頁
C#,ch5泛型.ppt_第5頁
已閱讀5頁,還剩55頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、5 Generics,Shuai L 2012.8.22,0. Introduction,Since the release of .NET 2.0, .NET has supported generics. Generics Generic classes (Chapter 5.2+5.1+5.3) Generic types Generic interfaces (Chapter 5.4) Generic structs (Chapter 5.5) Generic methods (Chapter 5.6),1. Creating Generic Classes,Non-generic s

2、implified linked list class public class LinkedListNode public LinkedListNode(object value) this.Value = value; public object Value get; private set; public LinkedListNode Next get; internal set; public LinkedListNode Prev get; internal set; ,1. Creating Generic Classes,public class LinkedList: IEnu

3、merable public LinkedListNode First get; private set; public LinkedListNode Last get; private set; public LinkedListNode AddLast(object node) public IEnumerator GetEnumerator() LinkedListNode current = First; while (current != null) yield return current.Value; current = current.Next; ,yield (Chapter

4、 6),Enumerations (Chapter 6),1. Creating Generic Classes,public LinkedListNode AddLast(object node) var newNode = new LinkedListNode(node); if (First = null) First = newNode; newNode.Prev = Last; Last = First; else LinkListNode previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previo

5、us; return newNode; ,1. Creating Generic Classes,var list1 = new LinkedList(); list1.AddLast(2); list1.AddLast(4); list1.AddLast(6); foreach (int i in list1) Console.WriteLine(i); ,As the integer types are converted to an object, boxing occurs. With the foreach statement, unboxing happens. (Chapter

6、7),In the foreach statement the elements from the list are cast to an integer, so with the third element in the list a runtime exception occurs as casting to an int fails.,1. Creating Generic Classes,Generic linked list class public class LinkedListNode public LinkedListNode(T value) this.Value = va

7、lue; public T Value get; private set; public LinkedListNode Next get; internal set; public LinkedListNode Prev get; internal set; ,1. Creating Generic Classes,public class LinkedList: IEnumerable public LinkedListNode First get; private set; public LinkedListNode Last get; private set; public Linked

8、ListNode AddLast(T node) public IEnumerator GetEnumerator() LinkedListNode current = First; IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); ,1. Creating Generic Classes,public LinkedListNode AddLast(T node) var newNode = new LinkedListNode (node); if (First = null) First = newNode; n

9、ewNode.Prev = Last; Last = First; else LinkListNode previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previous; return newNode; ,1. Creating Generic Classes,var list2 = new LinkedList (); list2.AddLast(1); list2.AddLast(3); list2.AddLast(5); foreach (int i in list2) Console.WriteLine

10、(i); ,Using the generic LinkedList , you can instantiate it with an int type, and there s no boxing.,Also, you get a compiler error if you don t pass an int with the method AddLast(). Using the generic IEnumerable , the foreach statement is also type-safe, and you get a compiler error if that variab

11、le in the foreach statement is not an int.,1. Creating Generic Classes,var list3 = new LinkedList (); list3.AddLast(2); list3.AddLast(four); list3.AddLast(foo); foreach (string s in list3) Console.WriteLine(s); ,2. Generics Features,Characters (特性/特征) Performance Type safety Binary code reuse Code b

12、loat Naming guidelines,Features (特征/特色) Default values Constraints Inheritance Static members,2. Generics Features,Performance Value types are stored on the stack. Reference types are stored on the heap. C# classes are reference types; structs are value types. .NET makes it easy to convert value typ

13、es to reference types, so you can use a value type everywhere an object is needed. Boxing and unboxing are easy to use but have a big performance impact, especially when iterating through many items.,2. Generics Features,var list = new ArrayList (); list.Add(44); / boxing convert a value type to a r

14、eference type int i1 = (int)list0; / unboxing convert a reference type to a value type foreach (int i2 in list) / unboxing Console.WriteLine(i2); var list = new List (); list.Add(44); / no boxing value types are stored in the List int i1 = list0; / no unboxing, no cast needed foreach (int i2 in list

15、) / no unboxing, no cast needed Console.WriteLine(i2); ,2. Generics Features,Performance (cont.) Collections namespaces System.Collections System.Collections.Generic Instead of using objects, the List class allows you to define the type when it is used.,2. Generics Features,Type safety As with the A

16、rrayList class, if objects are used, any type can be added to this collection. var list = new ArrayList(); list.Add(44); list.Add(mystring); list.Add(new MyClass(); foreach (int i in list) /a runtime exception will occur Console.WriteLine(i); ,2. Generics Features,Type safety (cont.) Errors should b

17、e detected as early as possible. With the generic class List, the generic type T defines what types are allowed. var list = new List(); list.Add(44); list.Add(mystring); / compile time error list.Add(new MyClass(); / compile time error,2. Generics Features,Binary code reuse A generic class can be de

18、fined once and can be instantiated with many different types. Generic types can be defined in one language and used from any other .NET language. var list = new List(); list.Add(44); var stringList = new List(); stringList.Add(mystring); var myClassList = new List(); myClassList.Add(new MyClass();,2

19、. Generics Features,Code bloat (Code extending) Because a generic class definition goes into the assembly, instantiating generic classes with specific types doesnt duplicate these classes in the IL code. However, when the generic classes are compiled by the JIT compiler to native code, a new class f

20、or every specific value type is created.,2. Generics Features,Naming guidelines Generic type names should be prefixed with the letter T. public class List public class LinkedList public delegate void EventHandler(object sender, TEventArgs e); public delegate TOutput Converter(TInput from); public cl

21、ass SortedList ,2. Generics Features,Default values using System; using System.Collections.Generic; namespace Wrox.ProCSharp.Generics public class DocumentManager private readonly Queue documentQueue = new Queue (); public void AddDocument(T doc) public bool IsDocumentAvailable public T GetDocument(

22、) public void DisplayAllDocuments() / Constraints ,2. Generics Features,public void AddDocument(T doc) lock (this) documentQueue.Enqueue(doc); public bool IsDocumentAvailable get return documentQueue.Count 0; ,2. Generics Features,public T GetDocument() T doc = default(T); / It is not possible to as

23、sign null to generic types. lock (this) doc = documentQueue.Dequeue(); return doc; ,It is not possible to assign null to generic types. The reason is that a generic type can also be instantiated as a value type, and null is allowed only with reference types.,2. Generics Features,Constraints public i

24、nterface IDocument string Title get; set; string Content get; set; ,public class Document: IDocument public Document() public Document(string title, string content) this.Title = title; this.Content = content; public string Title get; set; public string Content get; set; ,2. Generics Features,public

25、void DisplayAllDocuments() foreach (T doc in documentQueue) Console.WriteLine(IDocument)doc).Title); ,Doing a cast results in a runtime exception if type T does not implement the interface IDocument. Instead, it would be better to define a constraint with the DocumentManager class that the type T mu

26、st implement the interface IDocument.,2. Generics Features,public class DocumentManager where TDocument: IDocument public void DisplayAllDocuments() foreach (TDocument doc in documentQueue) / Console.WriteLine(IDocument)doc).Title); Console.WriteLine(doc.Title); ,2. Generics Features,static void Mai

27、n() var dm = new DocumentManager (); dm.AddDocument(new Document(Title A, Sample A); dm.AddDocument(new Document(Title B, Sample B); dm.DisplayAllDocuments(); if (dm.IsDocumentAvailable) Document d = dm.GetDocument(); Console.WriteLine(d.Content); ,2. Generics Features,Generics support several const

28、raint types,2. Generics Features,With a generic type, you can also combine multiple constraints. The constraint specifies that type T implements the interface IFoo and has a default constructor. public class MyClass where T: IFoo, new() /.,2. Generics Features,Inheritance A generic class can be deri

29、ved from a generic base class: The generic types of the interface must be repeated, or the type of the base class must be specified. public class Derived: Base / T1=T2 or T2 must be specified ,2. Generics Features,public abstract class Calc public abstract T Add(T x, T y); public abstract T Sub(T x,

30、 T y); public class IntCalc: Calc public override int Add(int x, int y) return x + y; public override int Sub(int x, int y) return x y; ,2. Generics Features,Static members Static members of a generic class are only shared with one instantiation of the class. Because the class StaticDemo is used wit

31、h both a string type and an int type, two sets of static fields exist. public class StaticDemo public static int x; StaticDemo.x = 4; StaticDemo.x = 5; Console.WriteLine(StaticDemo.x); / writes 4,3. Generic Interfaces,Some generic interfaces IEnumerableIEnumerator IComparableIComparer ICollection IL

32、ist IDictionary IExtensibleObject IDisplay IIndex ,3. Generic Interfaces,public class Person: IComparable public int CompareTo(object obj) Person other = obj as Person; return this.Lastname.CompareTo(other.LastName); public class Person: IComparable public int CompareTo(Person other) return this.Las

33、tName.CompareTo(other.LastName); ,3. Generic Interfaces,Covariance and contra-variance The conversion of types with argument and return types. public class Shape public double Width get; set; public double Height get; set; public override string ToString() return String.Format(Width: 0, Height: 1, W

34、idth, Height); public class Rectangle: Shape ,3. Generic Interfaces,Covariance and contra-variance parameter types are covariant. public void Display(Shape o) Rectangle r = new Rectangle Width= 5, Height=2.5; Display(r); Return types of methods are contra-variant. public Rectangle GetRectangle(); Sh

35、ape s = GetRectangle();,3. Generic Interfaces,Covariance with generic interfaces A generic interface is covariant if the generic type is annotated with the out keyword. public interface IIndex T thisint index get; int Count get; ,3. Generic Interfaces,public class RectangleCollection: IIndex private

36、 Rectangle data = new Rectangle3 new Rectangle Height=2, Width=5, new Rectangle Height=3, Width=7, new Rectangle Height=4.5, Width=2.9 ; public static RectangleCollection GetRectangles() return new RectangleCollection(); public Rectangle thisint index public int Count ,3. Generic Interfaces,public R

37、ectangle thisint index get if (index data.Length) throw new ArgumentOutOfRangeException(index); return dataindex; public int Count getreturn data.Length; ,3. Generic Interfaces,static void Main() IIndex rectangles = RectangleCollection.GetRectangles(); / covariant IIndex shapes = rectangles; for (in

38、t i = 0; i shapes.Count; i+) Console.WriteLine(shapesi); ,3. Generic Interfaces,Contra-Variance with generic interfaces A generic interface is contra-variant if the generic type is annotated with the in keyword. public interface IDisplay void Show(T item); ,3. Generic Interfaces,public class ShapeDi

39、splay: IDisplay public void Show(Shape s) Console.WriteLine(0 Width: 1, Height: 2, s.GetType().Name, s.Width, s.Height); ,3. Generic Interfaces,static void Main() IDisplay shapeDisplay = new ShapeDisplay(); /contra-variant IDisplay rectangleDisplay = shapeDisplay; rectangleDisplay.Show(rectangles0);

40、 ,4. Generic Structs,Nullable: T or null Instead of using syntax with the generic structure, the ? operator can be used. Nullable x1; int? x2; Non-nullable types can be converted to nullable types. With the conversion from a non-nullable type to a nullable type, an implicit conversion is possible wh

41、ere casting is not required. In the reverse situation, a conversion from a nullable type to a non-nullable type can fail.,4. Generic Structs,public struct Nullable where T: struct public Nullable(T value) this.hasValue = true; this.value = value; private bool hasValue; public bool HasValue get retur

42、n hasValue; private T value; public T Value public static explicit operator T(Nullable value) public static implicit operator Nullable(T value) public override string ToString() ,4. Generic Structs,private T value; public T Value get if (!hasValue) throw new InvalidOperationException(no value); retu

43、rn value; ,4. Generic Structs,public static explicit operator T(Nullable value) return value.Value; public static implicit operator Nullable(T value) return new Nullable(value); public override string ToString() if (!HasValue) return String.Empty; return this.value.ToString(); ,4. Generic Structs,Nu

44、llable x; x = 4; x += 3; if (x.HasValue) int y = x.Value; x = null;,4. Generic Structs,A nullable type can be compared with null and also numbers int? x = GetNullableType(); if (x = null) Console.WriteLine(x is null); else if (x 0) Console.WriteLine(x is smaller than 0); ,4. Generic Structs,Nullable

45、 types can also be used with arithmetic operators. If any of the nullable types have a null value, the result is null. int? x1 = GetNullableType(); int? x2 = GetNullableType(); int? x3 = x1 + x2; The coalescing operator uses the syntax ? to define a default value for the conversion in case the nulla

46、ble type has a value of null. int? x1 = GetNullableType(); int y1 = x1 ? 0;,5. Generic Methods,Example 1: Swap() Example 2: AccumulateSimple() Example 3: Generic methods with constraints Example 4: Generic methods with delegates Generic methods specialization,Example 1: Swap(),void Swap(ref T x, ref

47、 T y) T temp; temp = x; x = y; y = temp; int i = 4; int j = 5; Swap(ref i, ref j); Swap(ref i, ref j);,Example 2: AccumulateSimple(),public class Account public string Name get; private set; public decimal Balance get; private set; public Account(string name, Decimal balance) this.Name = name;this.Balan

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論