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

Lập trình Windows - Lập Trình C #- Lập Trình C Shap - Chương 5 docx

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 (662.58 KB, 57 trang )

Generics
Generics
Nội dung
Nội dung

An toàn kiểu lúc biên dịch (compile time type safety)

Overloaded methods

Constraints

Generic Classes and Structs

Generic Interfaces

Generic Methods

Generic Delegates

Generic Type Conversion

Nullable Types
2
Type Safety
Type Safety
(định kiểu an toàn)
(định kiểu an toàn)

Các ngôn ngữ .net (C#, C++, VB ) đều là những ngôn ngữ
được định kiểu mạnh (strong type) phải khai báo biến
rõ ràng trước khi sử dụng.



Nhưng các kiểu tập hợp (collection) lại không được hỗ
trợ kiểu an toàn( Type safety). Ví dụ kiểu ArrayList, chúng
cho phép ta lưu trữ tất cả các object bên trong chúng.
3
Ví dụ về an toàn kiểu
Ví dụ về an toàn kiểu

namespace TestApp
{ class Test
{
static void Main(string[] args)
{ ArrayList list = new ArrayList();
list.Add(3);
list.Add(4);
//list.Add(5.0);
int total = 0;
foreach(int val in list)
{ total = total + val; }
Console.WriteLine( "Total is {0}", total);
}
}
}
4
Type Safety of Generics
Type Safety of Generics

Do ArrayList luôn cast mọi thứ về lớp cơ sở Object,
nên không có cách nào để kiểm tra kiểu ở thời gian
biên dịch.


Dùng Generics sẽ loại trừ việc upcast thành Object và
làm cho compiler có thể kiểm tra kiểu được. Nhờ đó có
thể tạo collection an toàn kiểu ngay thời gian biên dịch
5
5


Compile-time type safety
Compile-time type safety

Phát hiện sai kiểu dữ liệu ở thời điểm biên dịch

Ví dụ 1: nếu Stack được dùng để lưu trữ giá trị
int , nếu push vào 1 string thì sẽ gây lỗi
(compile-time error).

Ví dụ 2: phương thức Sort chỉ có thể sắp xếp
các phần tử cùng kiểu dữ liệu.

Để bảo đảm compile-time type safety, phải tạo
các version kiểu khác nhau cho lớp Stack cũng
như phương thức Sort  nhiều bản copy cho
cùng 1 mã.
6
Generics
Generics

Generics là 1 tính chất mới của C#


Generic methods enable you to specify, with a single
method declaration, a set of related methods.

Generic classes enable you to specify, with a single
class declaration, a set of related classes.

Generic interfaces enable you to specify, with a single
interface declaration, a set of related interfaces.

Generics provide compile-time type safety.
7
Generic
Generic

Generic cho phép định kiểu an toàn (type safety).

Cho phép tạo ra một cấu trúc dữ liệu mà không cần phải
xác định đó là kiểu dữ liệu gì.

Tuy nhiên khi cấu trúc dữ liệu này được sử dụng, trình
biên dịch phải đảm bảo rằng kiểu dữ liệu được sử dụng
với nó là kiểu an toàn. Generic cũng tương đương vơi
Template trong C++ tuy nhiên việc sử dụng Generic trong
.net dễ dàng hơn nhiều so với Template.
8
From Overloaded methods
From Overloaded methods

Overloaded methods thường được dùng thực thi cùng 1
thao tác trên nhiều loại dữ liệu.


Ví dụ: một console application chứa 3 phương thức
overloaded PrintArray dùng để hiển thị các phần tử của
mảng int, mảng double và mảng char.
9
10
Overloaded methods
Overloaded methods

Trong phương thức PrintArray, loại phần tử mảng (int,
double or char) xuất hiện tại 2 vị trí trong mỗi phuơng
thức

Thay thế các loại này thành 1 tên chung (generic name)

Cả 3 phương thức sẽ có chung 1 dạng sau:
11
Generic method
Generic method

Nếu nhiều overloaded methods chỉ khác
nhau ở kiểu dữ liệu của các đối số, nên dùng
generic method.

Một khai báo generic method có thể được
gọi ở những thời điểm khác nhau với đối số
là những loại dữ liệu khác nhau.

Dựa vào loại dữ liệu của các đối số được
đưa vào generic method mà compiler điều

hành method một cách thích hợp.
12
Generic method declaration
Generic method declaration

Tất cả khai báo generic method phải có type
parameter list đặt trong <> tiếp ngay sau tên method.
 Ex: static void PrintArray< E >( E[] inputArray )

Mỗi type parameter list chứa 1 hay nhiều tham số
loại (type parameter) cách nhau bởi dấu phẩy.

Type parameter là 1 identifier thay thế cho tham
số thực.

Type parameter có thể được dùng để khai báo loại
dữ liệu trả về (return type) , loại dữ liệu của tham
số và loại của các biến cục bộ.
13
Generic method’s body
Generic method’s body

Phần thân của generic method được khai báo như một
method thông thường.

Tên tham số loại (Type parameter) được dùng trong suốt
method phải trùng loại với tên các loại đã được khai báo
trong danh sách tham số loại (type parameter).

Tham số loại (Type parameter) có thể được khai báo chỉ 1

lần trong danh sách các tham số loại (type parameter list)
<>nhưng có thể xuất hiện nhiều lần danh sách tham số
(parameter list) của method đó.

Ví dụ:
void SwapIfGreater<T>(ref T lhs, ref T rhs)
where T : System.IComparable<T>
{ ….}
14
Generic Methods
Generic Methods

Declare a generic Method:
[access modifier] <A Return Type>
GenericMethodName<A list of Generic Type Parameter>
(A list of Arguments)
{
//items
}
15
Generic Methods
Generic Methods

For example:
16
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;

rhs = temp;
}
Generic Methods
Generic Methods

The following code example shows one way to call the
method by using int for the type argument:

We can also omit the type argument and the compiler
will infer it. The following call to Swap is equivalent to
the previous call:
17
public static void TestSwap()
{
int a = 1;
int b = 2;
Swap<int>(ref a, ref b); System.Console.WriteLine(a + " " + b);
}
Swap(ref a, ref b);
Generic Methods
Generic Methods

Within a generic class, non-generic methods can
access the class-level type parameters, as follows:

Use constraints to enable more specialized operations
on type parameters in methods.
18
class SampleClass<T>
{

void Swap(ref T lhs, ref T rhs) { }
}
Generic Methods
Generic Methods

This version of Swap<T>, now named
SwapIfGreater<T>, can only be used with type
arguments that implement IComparable<T>
19
void SwapIfGreater<T>(ref T lhs, ref T rhs)
where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
Overloading generic method
Overloading generic method

Generic method có thể overloaded.

Một class có thể cung cấp 2 hay nhiều generic methods
có cùng tên nhưng tham số khác nhau.

Một generic method có thể overloaded với 1 method
generic khác hay với các method non-generic

20
void DoWork() { }
void DoWork<T>() { }
void DoWork<T, U>() { }
Generic classes
Generic classes

Lớp generic cung cấp cách thức mô tả 1 lớp độc lập với
loại dữ liệu (type-independent). Từ lớp này có thể tạo
các đối tượng với kiểu xác định ( reusability).

Khi biên dịch, compiler sẽ bảo đảm an toàn kiểu. Đến lúc
chạy thì hệ thống sẽ thay thế các tham số loại với đối số
thực .
21
Generic class
Generic class

A generic class declaration is similar to a non-generic
class declaration, except that the class name is followed
by a type parameter list
class Stack< E >

Type parameter list of a generic class can have one or
more type parameters separated by commas.
22
Name Overloading in generics
Name Overloading in generics

Generic types are overloaded based upon the

number of arguments in their type argument lists.
23
public class Container {}
public class Container<T> {}
public class Container<T, R> {}
//public class Container<X, Y> {}
23
Don’t appear with
public class Container<T, R> {}
simultaneously
Don’t appear with
public class Container<T, R> {}
simultaneously
Name Overloading in generics
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.
24
24
Distinguish declarations
Distinguish declarations

Có 2 loại khai báo: open type và constructed type.


25
25
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

×