Tải bản đầy đủ (.ppt) (122 trang)

Chapter 09 - Generic pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (419.83 KB, 122 trang )

Chapter 9. Generics
Hoang Anh Viet

HaNoi University of Technology
11
Micro softMicrosoft
Objectives
22
“This chapter introduces you to probably the most exciting feature
added to C# 2.0 and the CLR. Those familiar with C++ templates
will find generics somewhat familiar, though many fundamental
differences exist. Using generics, you can provide a shell of
functionality within which to define more specific types at run time.
Generics are most useful with collection types and provide great
efficiency compared to the collections used in previous .NET
versions .”
Micro softMicrosoft
Roadmap
9.1 Difference Betweet Generics and C++ Template
9.2 Efficency and Type Safety of Generics
9.3 Generic Type Definitions and Constructed Generics
9.4 Generic Classes and Structs
9.5 Generic Interfaces
9.6 Generic Method
9.7 Generic Delegates
9.8 Generic Type Conversion
9.9 Default Value Expression
9.10 Nullable Types
33
Micro softMicrosoft
Roadmap


9.11 Constructed Types Control Accessibility
9.12 Generic and Inheritance
9.13 Contraints
9.14 Contraints on Nonclass Types
9.15 Generic System Conllection
9.16Generic System Interfaces
9.17 Select Problems and Solutions
9.18 Conversion and Operations on Within Generic Types
9.19 Creating Constructed Types Dynamically
4
Micro softMicrosoft
9.1 Difference Betweet Generics and
C++ Template

C++ Template

Expansion of C++ templates is static.

C++ templates are always expanded at compile time. Therefore,
the C++ compiler must have access to all template types—
generally through header files.

It is impossible to package C++ templates into libraries , because
any types used to create the closed types from the template types
at compile time. That’s why all of the code for C++ template types
usually lives in headers.
55
Micro softMicrosoft
9.1 Difference Betweet Generics and
C++ Template


Generics

They can be packaged in assemblies and consumed later.

Constructed types are formed at run time instead of being form
at compile time.

In many ways, this makes generics more flexible.

Generics significantly differently at design time than C++
templates

The syntax for every other element in C# is based on the
corresponding C++ syntax to leverage existing knowledge.

But the designers have streamlined the syntax and removed
some of the verbosity.
66
Micro softMicrosoft
Roadmap
9.1 Difference Betweet Generics and C++ Template
9.2 Efficency and Type Safety of Generics
9.3 Generic Type Definitions and Constructed Generics
9.4 Generic Classes and Structs
9.5 Generic Interfaces
9.6 Generic Method
9.7 Generic Delegates
9.8 Generic Type Conversion
9.9 Default Value Expression

9.10 Nullable Types
77
Micro softMicrosoft
Efficency of Generics

The added efficiency when using value types in
collections is one of the greatest gains from generics
in C#.
o
The ArrayList maintains a collection of System.Object types
o
Any reference or value type that is added to an ArrayList is
implicitly upcast to Object.
o
If the items are value types, they must be boxed when they
are added to the list, and unboxed when they are retrieved.
Both the casting and the boxing and unboxing operations
decrease performance;
8
Micro softMicrosoft
Efficency of Generics

Use generics to avoid the casting and the boxing and
unboxing operations .

Example
9
List<int> list1 = new List<int>();
// No boxing, no casting:
list1.Add(3);

Micro softMicrosoft
Efficency of Generics

Use generics to create many kinds of class(interface, )
from a generic class(interface, ) instead of using many
classes(interfaces, ) which have the same form.

10
public void SomeMethod(long x ) {
public long t;
t= x*x;
Console.WriteLine(“Squere of x is :
{1}”,t);
}
public void SomeMethod(int x ) {
public int t;
t= x*x;
Console.WriteLine(“Squere of x is :
{1}”,t);
}
//Use generic SomeMethod
public void SomeMethod<T>(T x) {
public T t;
t= x*x;
Console.WriteLine(“Squere of x is :
{1}”,t);
}
//Call the SomeMethod(long x):
SomeMethod<long>(x);
//Call the SomeMethod(int x)

SomeMethod<int>(x).
Micro softMicrosoft
Type Safety of Generics

If we create a heterogeneous collection, and combine
strings and ints in a single ArrayList , it is more likely to
be a programming error, and this error will not be
detected until runtime.

Generics provide the solution to a limitation in earlier
versions of the CLR and the C# language in which
generalization is accomplished by casting types to and
from the universal base type Object
11
Micro softMicrosoft
Example
/*The .NET Framework 1.1 way to create a
list:*/
System.Collections.ArrayList list1 =
new
System.Collections.ArrayList();
list1.Add(3);
list1.Add(105);
System.Collections.ArrayList list2 =
new
System.Collections.ArrayList();
list2.Add("It is raining in Redmond.");
list2.Add("It is snowing in the
mountains.");
//No error.

1212
System.Collections.ArrayList list =
new System.Collections.ArrayList();
/* Add an integer to the list.*/
list.Add(3);
/*Add a string to the list. This will
compile, but may cause an error
later.*/
list.Add("It is raining in
Redmond.");
int t = 0;
/*This causes an
InvalidCastException
to be returned.*/
foreach (int x in list)
{
t += x;
}
Micro softMicrosoft
Type Safety of Generics

The other limitation is lack of compile-time type
checking; because an ArrayList casts everything to
Object, there is no way at compile-time to prevent
client code from doing something.

Using Generics to eliminate the need for the upcast to
System.Object and to make the compiler do type
checking .


Thanks to generic classes, We can create a collection
that is type-safe at compile-time.
1313
Micro softMicrosoft
Example
// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();
// No boxing, no casting:
list1.Add(3);
// Compile-time error:
// list1.Add("It is raining in Redmond.");
1414
Example
15
using System;
using System.Collections;
using System.Collections.Generic;
public class EntryPoint
{
static void Main() {
}
public void NonGeneric( Stack stack ) {
foreach( object o in stack ) {
int number = (int) o;
Console.WriteLine( number );
}//end of foreach
}//end of NonGeneric
public void Generic( Stack<int> stack ) {
foreach( int number in stack ) {
Console.WriteLine( number );

}
}
}
Micro softMicrosoft
Roadmap
9.1 Difference Betweet Generics and C++ Template
9.2 Efficency and Type Safety of Generics
9.3 Generic Type Definitions and Constructed Generics
9.4 Generic Classes and Structs
9.5 Generic Interfaces
9.6 Generic Method
9.7 Generic Delegates
9.8 Generic Type Conversion
9.9 Default Value Expression
9.10 Nullable Types
1616
Micro softMicrosoft
9.3 Generic Type Definitions and
Constructed Types

A generic type is a compiled type that is unusable until a closed
type is created from it.

A nongeneric type is also known as a closed type

Whereas generic type is known as an open type

However, it is possible to define a new open type via a generic
1717
public class MyClass<T>

{
private T innerObject;
}
public class Consumer<T>
{
private MyClass< Stack<T> > obj;
}
The obj which is defined
via a generic is a new
open type
Micro softMicrosoft
Remark

A generic type, Consumer<T>, is defined also contains a
field that is based on another generic type

The type of the Consumer<T>,obj field, MyClass<
Stack<T> > remains open until someone declares a
constructed type based on Consumer<T>, thus creating
a closed type for the contained field.
1818
Micro softMicrosoft
Roadmap
9.1 Difference Betweet Generics and C++ Template
9.2 Efficency and Type Safety of Generics
9.3 Generic Type Definitions and Constructed Generics
9.4 Generic Classes and Structs
9.5 Generic Interfaces
9.6 Generic Method
9.7 Generic Delegates

9.8 Generic Type Conversion
9.9 Default Value Expression
9.10 Nullable Types
1919
Micro softMicrosoft
9.4 Generic Classes and Structs

Declarations of all generic struct and class types follow the same
rules as those for regular struct and class types

A class declaration contains a type parameter list, it is, from that
point on, a generic type.

Any nested class declaration within the scope of a generic type is
a generic type itself. Because the enclosing type’s fully qualified
name requires a type argument in order to completely specify the
nested type.

Generic types are overloaded based upon the number of
arguments in their type argument lists.
2020
Micro softMicrosoft
Name Overloading in generics

The following example illustrates what I mean:
21
public class Container {}
public class Container<T> {}
public class Container<T, R> {}
//public class Container<X, Y> {}

21
Don’t appear with
public class Container<T, R> {}
simultaneously
Micro softMicrosoft
Name Overloading in generics

Each generic Container identifier distinguishs it with
another thanks to a number of type parameters.

The name overloading rules for generic declarations
are based on the count of type parameters rather than
the names given to their placeholders.
2222
Micro softMicrosoft
Distinguish declarations

Distinguish between declaration an open type and
declaration a constructed type.

2323
public class MyClass<T>
{
private Container<int>
field1;
private Container<T> field2;
}

Declare a constructed
type

Declare an open type
(or a generic type)
{
A constructed type
as well as a closed
type
A constructed type
as well as an open type
Micro softMicrosoft
Distinguish declarations

If we declare a generic type,we ‘ll declare what is
called an open type. It’s called that because its fully
specified type is not yet known.

When we declare another type based upon the
generic type definition, we declaring what’s called a
constructed type.
2424
Micro softMicrosoft
Type parameter identifiers within
generics

All identifiers are declared and are valid within a
specific scope.

Within the confines of a method, any local variable
identifiers declared within the curly braces of the
method are only available within that scope.
2525

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×