Nội dung• Định nghĩa generic • Phương thức generic • Lớp generic • Ủy nhiệm hàm generic • Giao diện generic • Phép ràng buộc... Phương thức generic• Sử dụng một hoặc nhiều tham số kiểu t
Trang 1Công nghệ NET
1 - Tổng quan NET Framework
Công nghệ NET
1 - Tổng quan NET Framework
GV: Lương Trần Hy Hiến, Khoa CNTT, ĐH Sư phạm TpHCM
Trang 2Chương 1: Giới thiệu công nghệ NET
Chương 1: Giới thiệu công nghệ NET
Trang 3Nội dung chính
• Lịch sử NET
• Thành phần của công nghệ NET
• Kiến trúc NET Framework
• Các tính năng mới
Trang 4.NET Framework
.NET 1.1 (Apr-2003)
VS NET 2003 Default: Server 2003
.NET 3.5 (Nov-2007) VS.NET 2008
Default: Windows 7
.NET 3.0 (Nov-2006) Default: Windows Vista, Server 2008
.NET 4.5 (Aug-2012) VS.NET 2012
Default: Windows 8, Windows Server 2012
Trang 5.NET Framework
• Bộ khung phát triển ứng dụng;
– Bốn ngôn ngữ chính:C#, VB.NET, C++.NET, Jscript.NET – Common Language Runtime – CLR (.NET Runtime): tương tự máy ảo Java
– Bộ thư viện Framework Class Library - FCL
Trang 6Kiến trúc NET Framework
Trang 7.NET Framework 4.0
Trang 8.NET Framework 4.0 Architecture
Trang 9Chương 2: Ngôn ngữ C#
Chương 2: Ngôn ngữ C#
Trang 10Nội dung chính
Nhắc lại & Bổ sung thêm một số kiến thức cần thiết về C#:
• Từ khóa var - Anonymous Type
• Optional & Named Parameters (Function)
• Automatic Properties, Object Initialize, Extension Method (OOP)
• Generic (Function, Collection & Class)
Trang 11Từ khóa var - Anonymous Type
• Mục đích: để khai báo biến (trong phạm vi hàm, phương thức)
• Yêu cầu: phải khởi tạo giá trị khi khai báo
• Kiểu dữ liệu: ngầm định kiểu dữ liệu của biến là kiểu của biểu thức bên phải phép gán
• Ví dụ:
var s = 0;//s kiểu int
s = “hienlth”;//báo lỗi, không chuyển từ string sang int được.
Trang 12Optional & Named Parameters
• Optional Parameters: Tham số mặc định
– Dùng trong trường hợp người dùng không truyền tham số (giống C++)
– Phải truyền đúng thứ tự Tham số mặc định phải truyền từ phải sang trái, liên tục nhau.
• Named Parameters: Tham số được đặt tên
– Có thể đổi thứ tự các tham số
– Ví dụ: static void Test(int size, string name){ …}
Test(name: "Perl", size: 5);
Test(6, "Net");
Test(7, name: "Google");
Trang 13Automatic Properties
• Tự động tạo ra các private field và những thao tác get/set mặc định
• Ví dụ:
get ; set ; }
}
• Sử dụng:
SinhVien sv = new SinhVien ();
sv.HoTen = “Nguyen Ngoc Han”;
Trang 14Object Initialize
• Khởi tạo Cơ bản:
– string s = “Công nghệ NET”;
• Khởi tạo qua fields/properties:
– Diem dinhA = new Diem();
Trang 15Initializers Example
public class SinhVien {
public string Ho;
public string Ten;
}
public class NhomSV {
public SinhVien SinhVien1, SinhVien2, SinhVien3;
}
static void Main( string [] args){
var sv1= new SinhVien {Ho = “Nguyen", Ten = “Ngoc Han“};
var sv2= new SinhVien {Ho = “Nguyen", Ten = “Ngoc Huy"};
var sv3= new SinhVien {Ho = “Nguyen", Ten = “Ngoc Ngan“};
var nhom = new NhomSV {
SinhVien1 = sv1, SinhVien2 = sv2, SinhVien3 = sv3 };
}
Trang 16// Thêm vào kiểu tập hợp
Nguoi p = new Nguoi () {
Ho = “Nguyen",
Ten = “Huy",
DiaChi = new Address() {
Duong = “280 An Duong Vuong St.", Quan = “Thu Duc“
}
};
Trang 17Implicitly Typed Variables
• Type of the variable induced from
expression
– Must include an initializer
– Can not be null
var i = 5;
var s = "Hello";
var d = 1.0; // Did you really mean a double?
var orders = new Dictionary<int,Order>();
var a = new Point { X = 0, Y = 1 };
Trang 18• Structural type equivalence
– Two anonymous types can be compatible
• Why in the world would we want these?
– Again, needed/useful for LINQ
Trang 19Anonymous Types Example
protected object AnonymousTypes() {
// *** Create Complex Types 'on the fly‘
var Customer = new {
Company = "West Wind" ,
Trang 20Anonymous Method Example
• Becomes quite cumbersome to create little methods for each specialization
– These methods are only used in one context.
• The use and declaration are disjoint
• Would be nice to have the declaration in-line
personList.RemoveAll( delegate(Person person) {
return person.DateOfBirth.Year < 1980;
});
Trang 21bool b = xs.Exists( delegate ( int x) { return x > y; });
Local y is free in body of anonymous method
Trang 22Anonymous Methods
• Further simplification
Button button = new Button();
Button.Click += delegate ( object sender, EventArgs arg) { Console.WriteLine( "clicked" ); };
Can be simplified as follows
Button.Click += delegate { Console.WriteLine( "clicked" ); };
Formal parameters can be omitted if they are not used in the method body
delegate void EventHandler (object sender, EventArgs arg);
Trang 23delegate int Adder ();
static Adder CreateAdder() {
int x = 0;
return delegate { x++; return x; };
}
public static void Main() {
Adder add = CreateAdder();
Output:
x++; return x;
0
dummy object delegate
add 1
The dummy object lives as long as the delegate object
Trang 24Anonymous Method Example
delegate void MyDelegate ();
class Program {
static MyDelegate Foo() {
int x = 1;
Console WriteLine( "Foo: x = {0}" , x);
MyDelegate d = delegate { x++; Console WriteLine( "delegate: x = {0}" , x); };
d(); d();
Console WriteLine( "Foo: x = {0}" , x);
MyDelegate d2 = delegate { x += 10; Console WriteLine( "second delegate: x = {0}" , x); };
second delegate: x = 13 delegate: x = 14
Foo: x = 14 second delegate: x = 24 - Main: Foo()();
Foo: x = 1 delegate: x = 2 delegate: x = 3 Foo: x = 3
second delegate: x = 13 delegate: x = 14
Foo: x = 14 second delegate: x = 24
static void Main(string[] args) {
Console WriteLine( " - Main: Foo()();" );
Foo()();
Console WriteLine( " - Main: Foo()();" );
Foo()();
} }
Trang 25Extension Method
• Phương thức được viết thêm vào một class
static hiện có mà không cần một cấp thừa kế, biên dịch lại, hoặc sửa đổi mã nguồn gốc.
• được viết dưới dạng phương thức tĩnh (static)
Trang 26Lambda Expressions
• Generalized function syntax
– x x + 1
– in C# 3.0, have x => x + 1
• From anonymous delegate syntax:
– delegate(int x) { return x + 1;}
• Can have implicitly typed variables
• Can have more than one variable
• Can have expression or statement body
Trang 27Lambda Expressions
• Expression or statement body
• Implicitly or explicitly typed parameters
• Examples:
x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
( int x) => x + 1 // Explicitly typed, expression body
( int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console WriteLine() // No parameters
personList.RemoveAll(p => p.DateOfBirth.Year < 1980);
Trang 28Lambda Expressions
• Lambda expressions participate in inference
process of type arguments of generic methods
• In initial phase, nothing is inferred from
arguments that are lambda expressions
• Following the initial phase, additional inferences are made from lambda expressions using an
iterative process
Trang 29foreach (T element in source)
yield return selector(element);
}
• If call Select(customers, c => c.Name);
– T, S mapped to appropriate types
Trang 30Lambda Expressions
• Generic extension method example:
• Calling extension method with lambda expression:
List<Customer> customers = GetCustomerList();
IEnumerable< string > names = customers.Select(c => c.Name);
• Rewriting extension method call:
IEnumerable< string > names = Sequence.Select<T, S>(customers, c => c.Name);
• T type argument is inferred to Customer based on source argument type
Sequence.Select<Customer, S>(customers, c => c.Name)
• c lambda expression argument type is inferred to Customer
Sequence.Select<Customer, S>(customers, (Customer c) => c.Name)
• S type argument is inferred to string based on return value type of the lambda
expression
Sequence.Select<Customer, string >(customers, (Customer c) => c.Name)
public static class Sequence {
public static IEnumerable<S> Select<T,S>(this IEnumerable<T> source, Func<T, S> selector) { foreach (T element in source) yield return selector(element); } }
Trang 31Lambda Expressions
• A lambda expression is a value, that does not have a type but can be implicitly converted to a compatible delegate type
delegate R Func<A,R>(A arg);
Func< int , int > f1 = x => x + 1;
Func< int , double > f2 = x => x + 1;
Func< double , int > f3 = x => x + 1; // Error double -> int
Trang 32Lambda Expressions
• Given the code
delegate R Func<A,R>(A arg);
static Z F<X,Y,Z>(X x, Func<X,Y> f1, Func<Y,Z> f2)
Trang 33Generics Problem
Trang 34Nội dung
• Định nghĩa generic
• Phương thức generic
• Lớp generic
• Ủy nhiệm hàm generic
• Giao diện generic
• Phép ràng buộc
Trang 36Phương thức generic
• Sử dụng một hoặc nhiều tham số kiểu tùy ý sau tên của phương thức VD:
void MyMethod< T >( T var1, T var2,…)
tham số của phương thức hoặc bên trong
phần thân của phương thức
• Ví dụ: phương thức generic hoán đổi 2 biến kiểu T: void Swap<T>(ref T var1, ref T var2)
Trang 37Lớp generic
• Cú pháp khai báo một class generic:
class MyClass<T>
Trong đó T là tham số kiểu
• Khi thể hiện cụ thể lớp đó, bạn thay thế tham
số kiểu bằng một đối số kiểu (type argument)
• Ví dụ:
MyClass<string> class1= new MyClass<string>();
MyClass<int> class2= new MyClass<int>();
Trang 38Couple<string, int> couple = new Couple<string, int>(”Age”, 29);
Khi đó:
couple.elementA sẽ có kiểu string nhận giá trị “Age”
couple.elementB sẽ có kiểu int nhận giá trị 29.
Trang 39Nạp chồng phương thức generic
• Các phương thức generic có thể được nạp chồng dựa vào chữ ký hoặc số các tham số kiểu trong một phương thức.
Trang 40Sử dụng từ khóa mặc định
• Nếu không biết trước việc kiểu mà bạn đang tạo sẽ là một kiểu tham chiếu hay tham trị Khi sử dụng giá trị mặc định sẽ gặp một số vấn đề:
void MyMethod<T>(T var) {
Trang 41Các phép ràng buộc
• Khi bạn thể hiện cụ thể class bằng việc sử
dụng một đối số kiểu không tuân thủ các quy tắc trình biên dịch sẽ thông báo lỗi
• Các quy tắc đó được gọi là phép ràng buộc
• Để khai báo ràng buộc, sử dụng từ khóa
Where
Trang 42Các phép ràng buộc
Ràng buộc Chú giải
where T: struct T phải là một kiểu giá trị.
where T : class T phải là kiểu tham chiếu (class,
interface, delegate, hoặc array)
where T : new() T phải có hàm khởi tạo không tham số
public Khi sử dụng cùng với các ràng buộc khác, new() phải là ràng buộc cuối cùng
where T : <base class name> T phải hoặc kế thừa từ một lớp cơ sở
where T : <interface name> T phải thực thi giao diện
where T : U T phải giống như U hoặc được dẫn xuất
từ U
Trang 43Ủy nhiệm hàm generic
• Có thể tạo ủy nhiệm hàm generic sử dụng
các tham số kiểu riêng của nó.
delegate void MyDelegate<T1,T2>(T1 id, T2 name);
• Phương thức được đóng gói có thể là một
phương thức không generic
public void MyMethod(int id, string name){…}
• Khi thể hiện cụ thể ủy nhiệm hàm, phải
cung cấp các đối số kiểu
MyDelegate<int, string> d = new MyDelegate<int,string> (mc.MyMethod);
Trang 44Ủy nhiệm hàm generic
• Bạn cũng có thể tạo ủy nhiệm hàm sử dụng
các tham số kiểu của class đóng gói
Trang 45Giao diện generic
• Khai báo giao diện generic tương tự như khai
báo class generic
• Khi thực thi giao diện generic bạn phải tuân thủ
các quy tắc giống như kế thừa từ class generic
interface MyInterface<T>
interface YourInterface<U>
interface MyInterface<T1,T2>
//Kế thừa giao diện
class MyClass: MyInterfac<double>{…}
Trang 46Ưu điểm của generic
• Các phần tử không cần phải boxing khi
được thêm vào hoặc casting khi được
truy tìm.
• Loại bỏ nhiều hao phí lập trình.
• Mã generic dễ đọc và dễ bảo trì hơn.
• Cung cấp một thực thi mã mẫu có thể tái
sử dụng
Trang 47• Không thể sử dụng các kiểu generic
trong mã không an toàn
• Các phương thức toán tử không thể là
những phương thức generic.
Trang 48Q & A
48
Trang 49THE END