Tuan05 c net advanced

19 0 0
Tuan05 c net advanced

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lập trình Windows 10/3/2018 1 C# NET nâng cao Lập trình Ứng dụng quản lý Nội dung  Generic Delegate  Events  Anonymous Methods  Lambda Expressions  Exceptions 10/3/2018 2 Nội dung  Generic Deleg[.]

10/3/2018 Lập trình Ứng dụng quản lý C#.NET nâng cao Nội dung  Generic Delegate  Events  Anonymous Methods  Lambda Expressions  Exceptions 10/3/2018 Nội dung  Generic Delegates  Events  Anonymous Methods  Lambda Expressions  Exceptions Generic Delegates  Tương tự với method, delegate cài đặt theo kiểu generic (nhằm làm tham số hàm chung cho số trường hợp) public delegate void MyDelegate(T param);  Trong NET khai báo sẵn số generic delegate như: Predicate, Action, Comparison,… 10/3/2018 Generic Delegates thông dụng  Predicate sử dụng để kiểm tra giá     trị có thỏa mãn điều kiện không trả kiểu bool Action sử dụng để thực hành động với đối tượng mà ta truyền vào không trả giá trị Comparison dùng để so sánh hai đối tượng kiểu, thường sử dụng trường hợp xếp … Ví dụ thường gặp phương thức tĩnh cung cấp class Array Ví dụ  class Array  Phương thức tìm kiếm T[] Array.FindAll(T[] array, Predicate match)  Phương thức duyệt mảng void Array.ForEach(T[] array, Action action)  Phương thức xếp void Array.Sort(T[] array, Comparison comparison) 10/3/2018 Cách sử dụng bool FuncPredicate(int value) { return value % == 0; } StringBuilder sb = new StringBuilder(); void FuncAction(int value) { sb.AppendFormat("{0}, ", value); } int FuncComparison(int x, int y) { return x.CompareTo(y); } void funcTest() { int[] arrInt = new int[] { 3, 5, 7, 2, 10, 43, 12, 34 }; //sử dụng Predicate int[] arrTemp = Array.FindAll(arrInt, new Predicate(FuncPredicate)); //sử dụng Action Array.ForEach(arrInt, new Action(FuncAction)); //sử dụng Comparison Array.Sort(arrInt, new Comparison(FuncComparison)); } Generic Delegates Action Func  Từ C# 3.0, Microsoft cung cấp kiểu delegate linh hoạt tiện dụng Action, Func  Action, Func cho phép khai báo tạo dạng delegate với số lượng tham số kiểu trả khác nhau, tương tự tạo method  Action, Func dùng chủ yếu để tạo lưu trữ anonymous method ngắn gọn lambda expression sử dụng method thông thường 10/3/2018 Syntax  Cú pháp để sử dụng Action, Func viết kiểu tham số giá trị trả vào cặp ngoặc ‘’, theo sau từ khóa Action, Func Action Func  Trong T kiểu tham số cần truyền vào TResult kiểu giá trị trả  Lưu ý Func yêu cầu tham số cặp ‘’, tức phải có kiểu trả Không để đặt void hay để cặp ngoặc ‘’ rỗng dùng Func Ví dụ static void DisplayMsg(string msg, Func func, Action action) { ConsoleColor previous = Console.ForegroundColor; if (func != null) { Console.ForegroundColor = func(msg); } int count = (new Random()).Next(2, 5); if (action != null) { action(msg, count); } Console.ForegroundColor = previous; } 10/3/2018 Các method  Cho Func static ConsoleColor GetColor(string msg) { if (msg.Length >= 10) return ConsoleColor.Red; if (msg.Length >= 7) return ConsoleColor.Yellow; if (msg.Length >= 4) return ConsoleColor.Blue; return ConsoleColor.White; }  Cho Action static void PrintMsg(string msg, int count) { for (int i = 0; i < count; i++) { Console.WriteLine(msg); } } Hàm main static void Main(string[] args) { var func = new Func(GetColor); var action = new Action(PrintMsg); DisplayMsg("Test Test", func, action); } 10/3/2018 Nội dung  Generic Delegates  Events  Anonymous Methods  Lambda Expressions  Exceptions Events  Event (sự kiện) hành động xảy trình chạy chương trình (gõ phím, click chuột, nhấn nút,…) thơng báo để xử lý thích hợp  Event khơng thể biết trước xác xảy ra, điều quan trọng phải xử lý thích hợp xảy  Cơ chế publishing subscribing nghĩa đối tượng publish tập hợp event để lớp khác cần xử lý xảy đăng ký (subscribe) vào danh sách nhận lớp publish phát sinh event tất lớp đăng ký nhận thông báo 10/3/2018 Bản chất  Trong NET chế event thực thi với delegate  Lớp publisher định nghĩa delegate lớp subscriber phải thực thi Khi kiện xuất phương thức lớp subscriber gọi thông qua delegate  Một phương thức dùng để xử lý kiện trình xử lý kiện (event handler)  Khai báo: public delegate void myEventHandler(); public event myEventHandler myEvent; public EventHandler myEvent; Ví dụ class TestEvent { public delegate void TestHandler(int n); public event TestHandler eventTest1, eventTest2; public void Run() { Random rd = new Random(); while (true) { int n = rd.Next(); if (n % == 0) eventTest1(n); else eventTest2(n); if (Console.ReadKey().KeyChar == 'q') return; } } } 10/3/2018 class Program { static void Main(string[] args) { TestEvent t = new TestEvent(); t.eventTest1 += t_eventTest1; t.eventTest2 += t_eventTest2; t.Run(); } static void t_eventTest2(int n) { Console.WriteLine("Le: {0}", n); } static void t_eventTest1(int n) { Console.WriteLine("Chan: {0}", n); } } EventHandler  Được cung cấp sẵn NET  Là event với delegate định nghĩa delegate void EventHandler(object sender, EventArgs e)  Sử dụng class CTest { public event EventHandler EvtChangeHandler; // } static void C_EvtChangeHandler(object sender, EventArgs e) { // } var c = new CTest(); c.EvtChangeHandler += C_EvtChangeHandler; 10/3/2018 Tạo Custom Event Arguments  Dẫn xuất EventArgs public class MyEventArgs : EventArgs { public string msg; }  Khai báo event phù hợp class CTest { public delegate void MyHandler(object sender, MyEventArgs e); public event MyHandler EvtMyHandler; }  Có liệu cần thiết args private static void C_EvtMyHandler(object sender, MyEventArgs e) { Console.WriteLine(e.msg); } EventHandler  Mặc định có sẵn NET  Là dạng generic delegate  Cho phép sử dụng event mặc định với custom event arguments public class MyEventArgs : EventArgs { public string msg; } class CTest { //public delegate void MyHandler(object sender, MyEventArgs e); //public event MyHandler EvtMyHandler; public event EventHandler EvtMyHandler; } 10 10/3/2018 Nội dung  Generic Delegates  Events  Anonymous Methods  Lambda Expressions  Exceptions Anonymous Methods  Anonymous method (tạm dịch phương thức vơ danh) phương thức khơng có tên khai báo với từ khóa delegate  Anonymous method cho phép tạo hành động cho delegate với cách viết inline  Cụ thể delegate void DelTest(int value); void funcTest() { DelTest dt = delegate(int value) { // }; } 11 10/3/2018 Truy xuất biến cục  Anonymous method truy xuất tham số ref hay out method cha  Anonymous method biến cục tên với biến method cha  Anonymous method truy xuất thành phần liệu class chứa  Anonymous method dùng tên biến chung với thành phần liệu class chứa Áp dụng Generic Delegate static void funcTest() { var sb = new StringBuilder(); int[] arrInt = new int[] { 3, 5, 7, 2, 10, 43, 12, 34 }; //sử dụng Predicate int[] arrTemp = Array.FindAll(arrInt, delegate (int value) { return value % == 0; }); //sử dụng Action Array.ForEach(arrInt, delegate (int value) { sb.AppendFormat("{0}, ", value); }); //sử dụng Comparison Array.Sort(arrInt, delegate (int x, int y) { return x.CompareTo(y); }); } 12 10/3/2018 Áp dụng cho callback method static void Main(string[] args) { var c = new CTest(); c.EvtMyHandler += delegate (object sender, MyEventArgs e) { Console.WriteLine(e.msg); }; c.EvtMyHandler += delegate (object sender, MyEventArgs e) { var str = e.msg.ToUpper(); Console.WriteLine(str); }; } Nội dung  Generic Delegates  Events  Anonymous Methods  Lambda Expressions  Exceptions 13 10/3/2018 Lambda Expressions  Có từ C# 3.0  Có thể nói so với anonymous method, lambda expression coi cải tiến đáng giá từ phiên C# 2.0 lên C# 3.0  Khi dùng anonymous method tạo hàm inline nhằm hạn chế việc khai báo hàm riêng lẻ không cần thiết, giúp mã lệnh ngắn gọn  Với lambda expression viết ngắn gọn dễ dàng nhờ việc cung cấp toán tử cú pháp mới, đồng thời thể “thông minh” compiler cách tự nhận diện kiểu liệu  Ngồi ra, cịn kĩ thuật để tạo kiểu expression tree Syntax  Dạng Lambda Expression sau: (input parameters) => expression  Dấu mở đóng ngoặc tùy chọn trường hợp có tham số, ngược lại bắt buộc  Nếu có nhiều tham số chúng phân cách dấu phẩy (,)  Kiểu liệu tham số khai báo tường minh không Nếu không khai báo, trình biên dịch tự xác định kiểu, nhiên số trường hợp, cần phải rõ kiểu liệu //sẽ báo lỗi s => s.Length; //cần khai báo kiểu liệu (string s) => s.Length; 14 10/3/2018 Ví dụ  Anonymous method var list = new List { 3, 5, 7, 2, 10, 43, 12, 34 }; var evens = list.FindAll(delegate (int i) { return (i % 2) == 0; });  Dạng đầy đủ var evens = list.FindAll((int i) => { return i % == 0; });  Dạng rút gọn var evens = list.FindAll((int i) => ((i % 2) == 0)); var evens = list.FindAll(i => (i % 2) == 0); Đặc điểm  Kiểu liệu tham số khai báo tường minh khơng tường minh  Có thể sử dụng {} () để bọc khối lệnh Có khác biệt loại???  Có thể loại bỏ cặp dấu bọc khối lệnh không cần thiết 15 10/3/2018 Truyền tham số Lambda Expression  Nhiều tham số var c = new CTest(); c.EvtMyHandler += (sender, e) => { Console.WriteLine(e.msg); };  Khơng có tham số Func func = () => (new Random()).Next(); Nội dung  Generic Delegates  Events  Anonymous Methods  Lambda Expressions  Exceptions 16 10/3/2018 Exceptions  Trong trình chương trình chạy có nhiều trường hợp xảy lỗi biết trước như: lỗi chia 0, lỗi sử dụng đối tượng null, lỗi đọc file không tồn (hoặc bị xóa),…  Để kiểm sốt xử lý lỗi NET định nghĩa class Exception cách thức xử lý (exception handling) Khối lệnh xử lý exception (try…catch…finally) try { // khối lệnh phát sinh lỗi } catch (Exception type) { // xử lý lỗi Khi khối lệnh try phát sinh } lỗi (quăng exception) khối catch (Exception type) catch tương ứng xử lý { // } … finally { // thu hồi resources } 17 10/3/2018 Ví dụ static void Main(string[] args) catch (DivideByZeroException e) { { Console.WriteLine(e.Message); try } { catch(InvalidCastException e) int i = 0; { if (Console.ReadKey().KeyChar == ' ') Console.WriteLine(e.Message); { } int n = 10 / i; finally } { else Console.WriteLine("finally "); } { char c = Convert.ToChar(true); } } } Throw exception  Có thể tự quăng exception cho bên xử lý static void Main(string[] args) { try { if (Console.ReadKey().KeyChar == ' ') { Console.WriteLine("normal "); } else { Console.WriteLine("error"); throw new Exception("need fix"); } } catch (Exception e) { Console.WriteLine(e.Message); } } 18 10/3/2018 Các property thông dụng  Property TargetSite: cung cấp thông tin chi tiết method phát sinh exception  Property StackTrace: cung cấp thông tin theo dõi nơi phát sinh exception  Property HelpLink: cho phép sử dụng cung cấp thông tin URL trang trợ giúp  Property Data: cho phép sử dụng lưu trữ thông tin dạng IDictionary Bài tập  Thực lại ví dụ Siêu thị với Khách hàng cách sử dụng event  Khách hàng cần thêm thông tin: địa chỉ, ngày sinh  Thêm chức năng:  Tìm kiếm khách hàng theo tiêu chí: họ tên, năm sinh, địa  Cộng điểm cho khách hàng có sinh nhật tháng  Sắp xếp khách hàng theo địa theo điểm tích lũy 19

Ngày đăng: 09/04/2023, 06:29

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan