Разделы презентаций


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

Содержание

19.1. Стек для чисел class MyFloatStack // Stack for floats{int StackPointer = 0;float [] StackArray; // Array of float ↑ floatfloat ↓public void

Слайды и текст этой презентации

Слайд 1В.В. Подбельский Иллюстрации к курсу лекций по дисциплине «Программирование» С#_19 Generics Использованы материалы

пособия Daniel Solis, Illustrated C# 2008.
Обобщения

В.В. Подбельский Иллюстрации к курсу лекций по дисциплине «Программирование» С#_19 Generics   Использованы материалы пособия Daniel

Слайд 219.1. Стек для чисел
class MyFloatStack // Stack for floats
{
int

StackPointer = 0;
float [] StackArray; // Array of float

float
float ↓
public void Push( float x ) // Input type: float
{... }
float

public float Pop() // Return type: float
{...}
...
}
19.1. Стек для чисел class MyFloatStack 	// Stack for floats{int StackPointer = 0;float [] StackArray; 		// Array

Слайд 319-2. Generic types are templates for types

19-2. Generic types are templates for types

Слайд 419-3. Generics and user-defined types

19-3. Generics and user-defined types

Слайд 519-4. Continuing with the Stack Example
class MyStack
{
int StackPointer

= 0;
T [] StackArray;
public void Push(T x ) {...}
public T

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

Слайд 619-5. Creating instances from a generic type

19-5. Creating instances from a generic type

Слайд 719-6. Declaring a Generic Class
Type parameters

class SomeClass

T1, T2 >
{ Normally, types would be used in these

positions.
↓ ↓
public T1 SomeVar = new T1();
public T2 OtherVar = new T2();
} ↑ ↑
Normally, types would be used in these positions.
19-6. Declaring a Generic Class 			Type parameters				 ↓class SomeClass < T1, T2 >{ Normally, types would be

Слайд 819-7. Creating a Constructed Type

19-7. Creating a Constructed Type

Слайд 919-8. Type parameters versus type arguments

19-8. Type parameters versus type arguments

Слайд 1019-9. Creating Variables and Instances
MyNonGenClass myNGC = new MyNonGenClass ();
Constructed

class Constructed class
↓ ↓
SomeClass mySc1 = new SomeClass();
var

mySc2 = new SomeClass();
19-9. Creating Variables and InstancesMyNonGenClass myNGC = new MyNonGenClass ();Constructed class 			Constructed class		↓ 					↓SomeClass mySc1 = new

Слайд 11 19-10.

19-10.

Слайд 1219-11. Two constructed classes created from a generic class

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

Слайд 1319-12. Constraints on Type Parameters
class Simple
{
static public bool LessThan(T

i1, T i2)
{
return i1 < i2; // Error
}
...
}

19-12. Constraints on Type Parameters class Simple{static public bool LessThan(T i1, T i2){return i1 < i2; //

Слайд 1419-13. Where Clauses
Type parameter Constraint list
↓ ↓
where TypeParam : constraint,

constraint, ...

Colon

nbounded With constraints
↓ ↓ No separators
class MyClass < T1, T2, T3 > ↓
where T2: Customer // Constraint for T2
where T3: Icomparable // Constraint for T3
{ ↑
... No separators
}
19-13. Where ClausesType parameter 		Constraint list		↓ 			↓where TypeParam : constraint, constraint, ...   			  ↑

Слайд 1519-14. Constraint Types and Order

19-14. Constraint Types and Order

Слайд 1619-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.

Слайд 1719-16. Правила задания ограничений
class SortedList
where S: IComparable { ... }
class

LinkedList
where M : IComparable
where N : ICloneable { ... }
class

MyDictionary
where KeyType : IEnumerable,
new() { ... }

19-16. Правила задания ограниченийclass SortedList		where S: IComparable { ... }class LinkedList		where M : IComparable		where N : ICloneable

Слайд 1819-17. Generic Structs
struct PieceOfData // Generic struct
{
public PieceOfData(T value) {

_Data = value; }
private T _Data;
public T Data
{
get { return

_Data; }
set { _Data = value; }
}
}

19-17. Generic Structsstruct PieceOfData // Generic struct{	public PieceOfData(T value) { _Data = value; }	private T _Data;	public T

Слайд 1919-18. Generic Structs
class Program {
static void Main() Constructed type
{ ↓
var

intData = new PieceOfData(10);
var stringData = new PieceOfData("Hi there.");

Constructed type
Console.WriteLine("intData

= {0}", intData.Data);
Console.WriteLine("stringData = {0}", stringData.Data);
}
}

19-18. Generic Structs class Program	{static void Main() 	Constructed type{ 					↓var intData = new PieceOfData(10);var stringData = new

Слайд 2019-19. Generic Interfaces
Type parameter

interface IMyIfc //

Generic interface
{ T ReturnIt(T inValue); }
Type parameter Generic interface


class Simple : IMyIfc // Generic class
{
public S ReturnIt(S inValue) // Implement interface
{ return inValue; }
}

19-19. Generic Interfaces 			Type parameter			   ↓interface IMyIfc 			// Generic interface{	T ReturnIt(T inValue);	}Type parameter 	Generic interface

Слайд 2119-20. Generic Interfaces
class Program{
static void Main(){
var trivInt = new

Simple();
var trivString = new Simple();
Console.WriteLine("{0}", trivInt.ReturnIt(5));
Console.WriteLine("{0}", trivString.ReturnIt("Hi there."));
}
}

This code produces

the following output:
5
Hi there.
19-20. Generic Interfaces class Program{static void Main(){	var trivInt = new Simple();	var trivString = new Simple();	Console.WriteLine(

Слайд 2219-21. Using Generic Interfaces
interface IMyIfc // Generic interface
{ T ReturnIt(T

inValue); }
Two different interfaces from the same generic interface
↓ ↓
class Simple :

IMyIfc, IMyIfc // Non-generic class
{
public int ReturnIt(int inValue) / / Implement int interface
{ return inValue; }
public string ReturnIt(string inValue) // Implement string interface
{ return inValue; }
}

19-21. Using Generic Interfaces interface IMyIfc 				// Generic interface{	T ReturnIt(T inValue);	}Two different interfaces from the same generic

Слайд 2319-22. Using Generic Interfaces
class Program {
static void Main() {
Simple trivInt =

new Simple();
Simple trivString = new Simple();
Console.WriteLine("{0}", trivInt.ReturnIt(5));
Console.WriteLine("{0}", trivString.ReturnIt("Hi there."));
}
}

This code

produces the following output:
5
Hi there.
19-22. Using Generic Interfaces class Program	{static void Main()	{	Simple trivInt = new Simple();	Simple trivString = new Simple();	Console.WriteLine(

Слайд 2419-23. Duplicate interface
interface IMyIfc { T ReturnIt(T inValue); }

class Simple :

IMyIfc, IMyIfc { // Error!
public int ReturnIt(int inValue)

// Implement first interface.
{ return inValue; }
public S ReturnIt(S inValue) // Implement second interface,
{ return inValue; } // but if it's int, it would be
// the same as the one above.
}

19-23. Duplicate interface  interface IMyIfc	{	T ReturnIt(T inValue);	}class Simple : IMyIfc, IMyIfc  {	// Error!public int ReturnIt(int

Слайд 2519-24. Generic Delegates
 
Type parameters

delegate R MyDelegate( T value

);
↑ ↑
Return

type Delegate formal parameter
 

19-24. Generic Delegates  				Type parameters					↓delegate R MyDelegate( T value );		  ↑

Слайд 2619-25. Generic delegate and matched delegate methods
delegate void MyDelegate(T value);

// Generic delegate

class Simple {
static public void PrintString(string s)
{ Console.WriteLine(s); }
static

public void PrintUpperString(string s)
{ Console.WriteLine("{0}", s.ToUpper()); }
}

19-25. Generic delegate and matched delegate methodsdelegate void MyDelegate(T value); 	// Generic delegateclass Simple	{static public void PrintString(string

Слайд 2719-26. Generic Delegate
class Program {
static void Main( ) {
var myDel =

// Create inst of delegate
new MyDelegate(Simple.PrintString);
myDel += Simple.PrintUpperString; // Add

a method.
myDel("Hi There."); // Call delegate
}
}

This code produces the following output:
Hi There.
HI THERE.

19-26. Generic Delegate class Program	{static void Main( )	{var myDel = 				// Create inst of delegate		new MyDelegate(Simple.PrintString);	myDel +=

Слайд 2819-27. Generic Delegate
public delegate TR Func(T1 p1,

T2 p2);
class Simple {
static public string PrintString(int p1, int

p2)
{ int total = p1 + p2; return total.ToString(); }
}
class Program {
static void Main() {
var myDel = new Func(Simple.PrintString);
Console.WriteLine("Total: {0}", myDel(15, 13));
}
}

19-27. Generic Delegate public delegate TR Func(T1 p1, T2 p2); class Simple 	{		static public string PrintString(int p1,

Слайд 2919-28. Generic Methods

19-28. Generic Methods

Слайд 3019-29. Declaring a Generic Method
Type parameter list Constraint clauses

↓ ↓
public void PrintData

T> ( S p ) where S: Person
{ ↑
…. Method parameter list
}

19-29. Declaring a Generic Method 		Type parameter list 		Constraint clauses				   ↓

Слайд 3119-30. Invoking a Generic Method
Объявление обобщенного метода:
void MyMethod() {
T1 someVar;
T2

otherVar;

}
Type arguments

MyMethod();
MyMethod();

19-30. Invoking a Generic Method	Объявление обобщенного метода:void MyMethod()	{	T1 someVar;	T2 otherVar;	…}					Type arguments  			 			 ↓				MyMethod();				MyMethod();

Слайд 3219-31. A generic method with two instantiations

19-31. A generic method with two instantiations

Слайд 3319-32. Inferring Types
public void MyMethod (T myVal) {

... }
↑ ↑
Both are

of type T
int MyInt = 5;
MyMethod (MyInt);
↑ ↑
Both are ints
MyMethod(MyInt);
19-32. Inferring Types 	public void MyMethod (T myVal) { ... }  				   	↑

Слайд 3419-33. Example of a Generic Method
class Simple { // Non-generic

class
static public void ReverseAndPrint(T[] arr) // Generic method
{
Array.Reverse(arr);
foreach (T item

in arr) // Use type argument T.
Console.Write("{0}, ", item.ToString());
Console.WriteLine("");
}
}

19-33. Example of a Generic Method class Simple {	// Non-generic classstatic public void ReverseAndPrint(T[] arr) // Generic

Слайд 3519-34. Example of a Generic Method
class Program {
static void Main() {
var

intArray = new int[] { 3, 5, 7, 9, 11

};
var stringArray = new string[] { "first", "second", "third" };
var doubleArray = new double[] { 3.567, 7.891, 2.345 };
Simple.ReverseAndPrint(intArray); // Invoke method
Simple.ReverseAndPrint(intArray); // Infer type and invoke
Simple.ReverseAndPrint(stringArray);
Simple.ReverseAndPrint(stringArray);
Simple.ReverseAndPrint(doubleArray);
Simple.ReverseAndPrint(doubleArray);
}
}
19-34. Example of a Generic Method class Program	{static void Main()	{	var intArray = new int[] { 3, 5,

Слайд 3619-35. Extension Methods with Generic Classes
static class ExtendHolder {
public static

void Print(this Holder h) {
T[] vals = h.GetValues();
Console.WriteLine("{0},\t{1},\t{2}", vals[0],

vals[1], vals[2]); }
}
class Holder {
T[] Vals = new T[3];
public Holder(T v0, T v1, T v2)
{ Vals[0] = v0; Vals[1] = v1; Vals[2] = v2; }
public T[] GetValues() { return Vals; }
}

19-35. Extension Methods with Generic Classes static class ExtendHolder	{public static void Print(this Holder h)	{ T[] vals =

Слайд 3719-36. Example
class Program {
static void Main(string[] args) {
var intHolder = new

Holder(3, 5, 7);
var stringHolder = new Holder("a1", "b2", "c3");
intHolder.Print();
stringHolder.Print();
}
}
This code

produces the following output:
3, 5, 7
a1, b2, c3

19-36. Exampleclass Program	{static void Main(string[] args) {	var intHolder = new Holder(3, 5, 7);	var stringHolder = new Holder(

Обратная связь

Если не удалось найти и скачать доклад-презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое TheSlide.ru?

Это сайт презентации, докладов, проектов в PowerPoint. Здесь удобно  хранить и делиться своими презентациями с другими пользователями.


Для правообладателей

Яндекс.Метрика