В. В. Подбельский Иллюстрации к курсу лекций по

  • Размер: 361 Кб
  • Количество слайдов: 38

Описание презентации В. В. Подбельский Иллюстрации к курсу лекций по по слайдам

В. В. Подбельский Иллюстрации к курсу лекций по дисциплине  «Программирование» С #_ 19 Generics В. В. Подбельский Иллюстрации к курсу лекций по дисциплине «Программирование» С #_ 19 Generics Использованы материалы пособия Daniel Solis, Illustrated C# 2008. Обобщения

19. 1. Стек для чисел class My. Float. Stack // Stack for floats { int Stack.19. 1. Стек для чисел class My. Float. Stack // Stack for floats { int Stack. Pointer = 0; float [] Stack. Array; // Array of float ↑ float ↓ public void Push( float x ) // Input type: float {. . . } float ↓ public float Pop() // Return type: float {. . . }

19 -2.  Generic types are templates for types 19 -2. Generic types are templates for types

19 -3.  Generics and user-defined types  19 -3. Generics and user-defined types

19 -4.  Continuing with the Stack Example  class My. Stack  T  {19 -4. Continuing with the Stack Example class My. Stack { int Stack. Pointer = 0; T [] Stack. Array; public void Push( T x ) {. . . } public T Pop() {. . . }

19 -5.  Creating instances from a generic type  19 -5. Creating instances from a generic type

19 -6.  Declaring a Generic Class  Type parameters  ↓ class Some. Class 19 -6. Declaring a Generic Class Type parameters ↓ class Some. Class { Normally, types would be used in these positions. ↓ ↓ public T 1 Some. Var = new T 1(); public T 2 Other. Var = new T 2(); } ↑ ↑ Normally, types would be used in these positions.

19 -7.  Creating a Constructed Type  19 -7. Creating a Constructed Type

1 9 -8.  Type parameters versus type arguments  1 9 -8. Type parameters versus type arguments

19 -9. Creating Variables and Instances My. Non. Gen. Class my. NGC = new My. Non.19 -9. Creating Variables and Instances My. Non. Gen. Class my. NGC = new My. Non. Gen. Class (); Constructed class ↓ ↓ Some. Class my. Sc 1 = new Some. Class(); var my. Sc 2 = new Some. Class();

19 -10.  19 -10.

19 -11.  Two constructed classes created from a generic class  19 -11. Two constructed classes created from a generic class

19 -12. Constraints on Type Parameters class SimpleT { static public bool Less. Than(T i 1,19 -12. Constraints on Type Parameters class Simple { static public bool Less. Than(T i 1, T i 2) { return i 1 < i 2; // Error }. . . }

19 -13.  Where Clauses Type parameter Constraint list ↓ ↓ where Type. Param : 19 -13. Where Clauses Type parameter Constraint list ↓ ↓ where Type. Param : constraint , . . . ↑ Colon nbounded With constraints ↓ ↓ No separators class My. Class ↓ where T 2: Customer // Constraint for T 2 where T 3: Icomparable // Constraint for T 3 { ↑. . . No separators }

19 -14.  Constraint Types and Order  Constr aint Type Description Class. Na me Only19 -14. Constraint Types and Order Constr aint Type Description Class. Na me Only classes of this type, or classes derived from it, can be used as the type argument. class Any reference type, including classes, arrays, delegates, and interfaces, can be used as the type argument. struct Any value type can be used as the type argument. Interfac e. Name Only this interface, or types that implement this interface, can be used as the type argument. new() Any type with a parameterless public constructor can be used as the type argument. This is called the constructor constraint.

19 -15. If a type parameter has multiple constraints, they must be in this order. 19 -15. If a type parameter has multiple constraints, they must be in this order.

19 -16. Правила задания ограничений class Sorted. ListS where S: IComparableS {. . . } class19 -16. Правила задания ограничений class Sorted. List where S: IComparable {. . . } class Linked. List where M : IComparable where N : ICloneable {. . . } class My. Dictionary where Key. Type : IEnumerable, new() {. . . }

19 -17.  Generic Structs struct Piece. Of. DataT // Generic struct { public Piece. Of.19 -17. Generic Structs struct Piece. Of. Data // Generic struct { public Piece. Of. Data(T value) { _Data = value; } private T _Data; public T Data { get { return _Data; } set { _Data = value; } } }

19 -18.  Generic Structs  class Program { static void Main() Constructed type { ↓19 -18. Generic Structs class Program { static void Main() Constructed type { ↓ var int. Data = new Piece. Of. Data(10); var string. Data = new Piece. Of. Data(«Hi there. «); ↑ Constructed type Console. Write. Line(«int. Data = {0}», int. Data); Console. Write. Line(«string. Data = {0}», string. Data); } }

19 -19.  Generic Interfaces  Type parameter  ↓ interface IMy. IfcT // Generic interface19 -19. Generic Interfaces Type parameter ↓ interface IMy. Ifc // Generic interface { T Return. It(T in. Value); } Type parameter Generic interface ↓ ↓ class Simple : IMy. Ifc // Generic class { public S Return. It(S in. Value) // Implement interface { return in. Value; } }

19 -20.  Generic Interfaces  class Program{ static void Main(){ var triv. Int = new19 -20. Generic Interfaces class Program{ static void Main(){ var triv. Int = new Simple(); var triv. String = new Simple(); Console. Write. Line(«{0}», triv. Int. Return. It(5)); Console. Write. Line(«{0}», triv. String. Return. It(«Hi there. «)); } } This code produces the following output: 5 Hi there.

19 -21.  Using Generic Interfaces  interface IMy. IfcT // Generic interface { T Return.19 -21. Using Generic Interfaces interface IMy. Ifc // Generic interface { T Return. It(T in. Value); } Two different interfaces from the same generic interface ↓ ↓ class Simple : IMy. Ifc, IMy. Ifc // Non-generic class { public int Return. It(int in. Value) / / Implement interface { return in. Value; } public string Return. It(string in. Value) // Implement string interface { return in. Value; } }

19 -22.  Using Generic Interfaces class Program { static void Main() { Simple triv. Int19 -22. Using Generic Interfaces class Program { static void Main() { Simple triv. Int = new Simple(); Simple triv. String = new Simple(); Console. Write. Line(«{0}», triv. Int. Return. It(5)); Console. Write. Line(«{0}», triv. String. Return. It(«Hi there. «)); } } This code produces the following output: 5 Hi there.

19 -23.  Duplicate interface IMy. IfcT { T Return. It(T in. Value); } class SimpleS19 -23. Duplicate interface IMy. Ifc { T Return. It(T in. Value); } class Simple : IMy. Ifc, IMy. Ifc { // Error! public int Return. It(int in. Value) // Implement first interface. { return in. Value; } public S Return. It(S in. Value) // Implement second interface, { return in. Value; } // but if it’s int, it would be // the same as the one above. }

19 -24.  Generic Delegates  Type parameters ↓ delegate R My. DelegateT, R( T value19 -24. Generic Delegates Type parameters ↓ delegate R My. Delegate( T value ); ↑ Return type Delegate formal parameter

19 -25.  Generic delegate and matched delegate methods delegate void My. DelegateT(T value);  //19 -25. Generic delegate and matched delegate methods delegate void My. Delegate(T value); // Generic delegate class Simple { static public void Print. String(string s ) { Console. Write. Line(s); } static public void Print. Upper. String(string s) { Console. Write. Line(«{0}», s. To. Upper()); } }

19 -26.  Generic Delegate  class Program { static void Main( ) { var my.19 -26. Generic Delegate class Program { static void Main( ) { var my. Del = // Create inst of delegate new My. Delegate(Simple. Print. String); my. Del += Simple. Print. Upper. String; // Add a method. my. Del(«Hi There. «); // Call delegate } } This code produces the following output: Hi There. HI THERE.

19 -27.  Generic Delegate public delegate TR FuncT 1, T 2, TR(T 1 p 1,19 -27. Generic Delegate public delegate TR Func(T 1 p 1, T 2 p 2); class Simple { static public string Print. String(int p 1, int p 2) { int total = p 1 + p 2; return total. To. String(); } } class Program { static void Main() { var my. Del = new Func(Simple. Print. String); Console. Write. Line(«Total: {0}», my. Del(15, 13)); } }

19 -2 8.  Generic Methods 19 -2 8. Generic Methods

19 -2 9. Declaring a Generic Method  Type parameter list Constraint clauses  ↓ 19 -2 9. Declaring a Generic Method Type parameter list Constraint clauses ↓ ↓ public void Print. Data ( S p ) where S: Person { ↑ …. Method parameter list }

19 - 30.  Invoking a Generic Method Объявление обобщенного метода : void My. MethodT 1,19 — 30. Invoking a Generic Method Объявление обобщенного метода : void My. Method() { T 1 some. Var; T 2 other. Var; … } Type arguments ↓ My. Method(); My. Method();

19 - 3 1.  A generic method with two instantiations 19 — 3 1. A generic method with two instantiations

19 - 3 2. Inferring Types  public void My. Method T (T my. Val) {.19 — 3 2. Inferring Types public void My. Method (T my. Val) {. . . } ↑ ↑ Both are of type T int My. Int = 5; My. Method (My. Int); ↑ ↑ Both are ints My. Method(My. Int);

19 - 3 3.  Example of a Generic Method class Simple { // Non-generic class19 — 3 3. Example of a Generic Method class Simple { // Non-generic class static public void Reverse. And. Print(T[] arr) // Generic method { Array. Reverse(arr); foreach (T item in arr) // Use type argument T. Console. Write(«{0}, «, item. To. String()); Console. Write. Line(«»); } }

19 - 3 4.  Example of a Generic Method class Program { static void Main()19 — 3 4. Example of a Generic Method class Program { static void Main() { var int. Array = new int[] { 3, 5, 7, 9, 11 }; var string. Array = new string[] { «first», «second», «third» }; var double. Array = new double[] { 3. 567, 7. 891, 2. 345 }; Simple. Reverse. And. Print(int. Array); // Invoke method Simple. Reverse. And. Print(int. Array); // Infer type and invoke Simple. Reverse. And. Print(string. Array); Simple. Reverse. And. Print(double. Array); Simple. Reverse. And. Print(double. Array); } }

19 - 3 5. Extension Methods with Generic Classes  static class Extend. Holder { public19 — 3 5. Extension Methods with Generic Classes static class Extend. Holder { public static void Print(this Holder h) { T[] vals = h. Get. Values(); Console. Write. Line(«{0}, \t{1}, \t{2}», vals[0], vals[1], vals[2]); } } class Holder { T[] Vals = new T[3]; public Holder(T v 0, T v 1, T v 2) { Vals[0] = v 0; Vals[1] = v 1; Vals[2] = v 2; } public T[] Get. Values() { return Vals; } }

19 - 3 6.  Example class Program { static void Main(string[] args) { var int.19 — 3 6. Example class Program { static void Main(string[] args) { var int. Holder = new Holder(3, 5, 7); var string. Holder = new Holder(«a 1», «b 2», «c 3»); int. Holder. Print(); string. Holder. Print(); } } This code produces the following output: 3, 5, 7 a 1, b 2, c

19 - 3 7.  19 — 3 7.