Bài giảng Bổ trợ Một số điểm khác của C# so với C ++

System.IO

 Cung cấp nhiều lớp cho vào/ra

 Các lớp File và Directory sử dụng để quản lý thư mục và tệp

 Các thao tác bao gồm sao chép (copying),

di chuyển (moving), đổi tên (renaming) và

xóa (deleting) các tệp và thư mục

pdf62 trang | Chia sẻ: maiphuongdc | Lượt xem: 2017 | Lượt tải: 1download
Bạn đang xem trước 20 trang tài liệu Bài giảng Bổ trợ Một số điểm khác của C# so với C ++, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
n 1 / 18 of 45 Tất cả các kiểu dữ liệu trong C# ñều kế thừa từ kiểu cơ sở object using System; class ObjectProff { public static void Main() { string objectVal; objectVal = 7.ToString(); Console.WriteLine (“The value now is ”+objectVal); } } 10 C# Simplified / Session 1 / 19 of 45 Cấu trúc có cả phương thức struct SINHVIEN { public string hoten; public byte tuoi; public void datTen(string ht) { hoten = ht; } } C# Simplified / Session 1 / 20 of 45 Kiểu liệt kê (Enumerators) public enum WeekDays { Monday, Tuesday, Wednesday, Thursday, Friday } Theo mặc ñịnh, các giá trị liệt kê lần lượt là 0, 1, 2, … Ví dụ, với kiểu liệt kê trên, Monday = 0, Friday = 4 11 C# Simplified / Session 1 / 21 of 45 Kiểu liệt kê  Có thể ñịnh lại giá trị cho các thành phần liệt kê public enum WeekDays { Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5 } C# Simplified / Session 1 / 22 of 45 Chồng phương thức Hai cách chồng phương thức –  Số lượng tham số khác nhau  Kiểu của tham số khác nhau 12 C# Simplified / Session 1 / 23 of 45 Chồng phương thức – Số lượng tham số khác nhau using System; public class Area { private int areaVal; public void AreaCal(int radius) { areaVal = (22/7)* radius*radius; } public void AreaCal(int length, int breadth) { areaVal = length*breadth; } public void AreaCal(int length, int breadth, int height) { areaVal = length*breadth*height; } … } C# Simplified / Session 1 / 24 of 45 Chồng phương thức – Tham số khác kiểu ... public void Add(int number1, int number2) { sum = number1 + number2; } public void Add(string value1, string value2) { int sum; sum = Int32.Parse(value1) + Int32.Parse(value2); Console.WriteLine ("Sum is {0}",sum); Console.WriteLine ("Strings are converted to integers to add”); } ... 13 C# Simplified / Session 1 / 25 of 45 Chồng toán tử  Các toán tử sau ñược phép ñịnh nghĩa chồng C# Simplified / Session 1 / 26 of 45 Chồng toán tử using System; public class Distance { int longitude, latitude; public Distance() { longitude = 0; latitude = 0; } public Distance(int longitude, int latitude) { this.longitude = longitude; this.latitude = latitude; } public static Distance operator - (Distance first, Distance second) { return new Distance(first.longitude - second.longitude, first.latitude - second.latitude); } //main } public static void Main() { Distance start = new Distance(); Distance objDistance = new Distance(); Distance finish = new Distance(); start.longitude = 12; start.latitude = 10; finish.longitude = 2; finish.latitude = 1; objDistance = start - finish; Console.WriteLine ("The Finish is {0} Degrees East and {1} Degrees North of the Start.", objDistance.longitude,objDistance.latitude); } This statement does not return an error as the ‘-’ operator is overloaded 14 C# Simplified / Session 1 / 27 of 45 Lớp bị bao bọc (Sealed Class) Không cho lớp nào kế thừa từ nó Sử dụng từ khóa ‘sealed’. … sealed class classOne { //Class Implementation } … C# Simplified / Session 1 / 28 of 45 Lớp trừu tượng  Lớp trừu tượng là lớp ñược sử dụng ñể kế thừa và không thể bao bọc nó  C# sử dụng từ khóa abstract trước ñịnh nghĩa lớp ñể chỉ một lớp là lớp trừu tượng  Một lớp trừu tượng có thể có phương thức không trừu tượng  Khi muốn viết lại một phương thức trừu tượng ở lớp kế thừa, ta dùng từ khóa override 15 C# Simplified / Session 1 / 29 of 45 Lớp trừu tượng – Ví dụ using System; abstract class BaseClass { public abstract void MethodA(); public void MethodB() { Console.WriteLine ("This is the non abstract method”); } } class DerivedClass : BaseClass { public override void MethodA() { Console.WriteLine ("This is the abstract method overriden in derived class"); } } C# Simplified / Session 1 / 30 of 45 class AbstractDemo { public static void Main() { DerivedClass objDerived = new DerivedClass(); BaseClass objBase = objDerived; objBase.MethodA(); objDerived.MethodB(); } } 16 C# Simplified / Session 1 / 31 of 45 Giao diện (Interfaces)  Giao diện là lớp trừu tượng chỉ chứa các phương thức trừu tượng mà mỗi phương thức chỉ có chữ ký, không có thân  Lớp kế thừa một giao diện phải cài ătj tất cả các phương thức của giao diện public interface IFile { int delFile(); void disFile(); } C# Simplified / Session 1 / 32 of 45 Giao diện – Ví dụ public interface IFile { int delFile(); void disFile(); } public class MyFile : IFile { public int delFile() { System.Console.WriteLine ("DelFile Implementation!"); return(0); } public void disFile() { System.Console.WriteLine ("DisFile Implementation!"); } } 17 C# Simplified / Session 1 / 33 of 45 Giao diện - Output class InterfaceDemo { public static void Main() { MyFile objMyFile = new MyFile(); objMyFile.disFile(); int retValue = objMyFile.delFile(); } } public class BaseforInterface { public void open() { System.Console.WriteLine ("This is the open method of BaseforInterface"); } } C# Simplified / Session 1 / 34 of 45 Giao diện – Kế thừa public interface IFile { int delFile(); void disFile(); } public class BaseforInterface { public void open() { System.Console.WriteLine ("This is the open method of BaseforInterface"); } } 18 C# Simplified / Session 1 / 35 of 45 Giao diện – Kế thừa public class MyFile : BaseforInterface, IFile { public int delFile() { System.Console.WriteLine ("DelFile Implementation!"); return(0); } public void disFile() { System.Console.WriteLine ("DisFile Implementation!"); } } C# Simplified / Session 1 / 36 of 45 Giao diện – Output về kế thừa class Test { static void Main() { MyFile objMyFile = new MyFile(); objMyFile.disFile(); int retValue = objMyFile.delFile(); objMyFile.open(); } } 19 C# Simplified / Session 1 / 37 of 45 Kế thừa từ nhiều giao diện public interface IFileTwo { void applySecondInterface(); } C# Simplified / Session 1 / 38 of 45 Kế thừa nhiều giao diện public class MyFile : BaseforInterface, IFile, IFileTwo { public int delFile() { System.Console.WriteLine ("DelFile Implementation!"); return(0); } public void disFile() { System.Console.WriteLine ("DisFile Implementation!"); } public void applySecondInterface() { System.Console.WriteLine ("ApplySecondInterface Implementation!"); } } 20 C# Simplified / Session 1 / 39 of 45 Kế thừa nhiều giao diện - Output class MultipleInterfaces { public static void Main() { MyFile objMyFile = new MyFile(); objMyFile.disFile(); int retValue = objMyFile.delFile(); objMyFile.open(); objMyFile.applySecondInterface(); } } C# Simplified / Session 1 / 40 of 45 Namespaces  Một namespace (không gian tên) là một ñơn vị logic của phần mềm bao gồm một hoặc nhiều lớp  Namespace ñược sử dụng ñể  tổ chức mã nguồn  tránh xung ñột tên  giảm ñộ phức tạp khi sử dụng lại 21 C# Simplified / Session 1 / 41 of 45 Tổ chức mã nguồn với namespaces NameSP1 NameSP2 NameSP11 NameSP12 Class1 Class2 Class1 Class3 Class2 Class1 Class2 Class1 Class2 Class3 C# Simplified / Session 1 / 42 of 45 Ví dụ khai báo Namespace class SamsungTelevision { ... } class SamsungWalkMan { ... } class SonyTelevision { ... } class SonyWalkMan { ... } namespace Samsung { class Television {...} class WalkMan {...} } namespace Sony { class Television {...} class Walkman {...} } 22 C# Simplified / Session 1 / 43 of 45 Namespaces lồng nhau Khai báo namespace trong namespace khác namespace Sony { namespace Television { class T14inches { ... } class T21inches { ... } } } ... namespace Sony.Television { class T14inches { ... } class T21inches { ... } } ... C# Simplified / Session 1 / 44 of 45 Namespaces & Bổ ngữ truy cập  Namespaces mặc ñịnh là public  Namespaces không thể là protected, private hoặc internal ... public namespace Sony //error { ... } private namespace Samsung //error { ... } ... 23 C# Simplified / Session 1 / 45 of 45 Namespace.classname Tên ñầy ñủ  ðể sử dụng một lớp trong cùng namespace, chúng ta chỉ cần sử dụng tên lớp (tên không ñầy ñủ)  ðể sử dụng lớp ngoài namespace, chúng ta phải sử dụng tên ñầy ñủ C# Simplified / Session 1 / 46 of 45 Tên không ñầy ñủ namespace Sony { class Television { ... } class WalkMan { ... Television MyTV = new Television(); //MyTV là Sony.Television } } 24 C# Simplified / Session 1 / 47 of 45 Tên ñầy ñủ - Ví dụ using Sony; using Samsung; using System; namespace Sony { namespace Television { class T14inches { public T14inches() { Console.WriteLine ("A 14 inches Television"); } } class T21inches { public T21inches() { Console.WriteLine ("A 21 inches Television"); } } }//end of namespace Television }//end of namespace Sony C# Simplified / Session 1 / 48 of 45 Tên ñầy ñủ - Ví dụ namespace Samsung { class Television { Sony.Television.T14inches myTV = new Sony.Television.T14inches(); } } class Test { static void Main() { Samsung.Television myTV = new Samsung.Television(); } } 25 C# Simplified / Session 1 / 49 of 45 Sử dụng chỉ dẫn namespace Sony.Television.T14inches tv = new Sony.Television.T14inches(); ... using Sony.Television; T14inches tv1 = new T14inches(); T21inches tv2 = new T21inches(); C# Simplified / Session 1 / 50 of 45 Các tên nhập nhằng tv là nhập nhằng vì không biết là Sosy.Television hay Samsung.Television? using Sony; using Samsung; class Test { static void Main() { Television tv = new Television(); //lỗi } } 26 C# Simplified / Session 1 / 51 of 45 Sử dụng tên ñầy ñủ ñể tránh nhập nhằng using Sony; using Samsung; class Test { static void Main() { Samsung.Television tv = new Samsung.Television(); } } C# Simplified / Session 1 / 52 of 45 using alias_name = fully qualified path to the namespace or class Sử dụng chỉ dẫn alias (bí danh) Sử dụng chỉ dẫn alias ñể tránh phải viết dài using T21inches = Sony.Televisions.T21inches; class Test { static void Main() { T21inches M = new T21inches(); } } 27 C# Simplified / Session 1 / 53 of 45 Thư viện các lớp cơ sở Base Class Library - BCL  Bao gồm một tập các lớp và phương thức ñược viết sẵn giúp xử lý những tác vụ hay ñược sử dụng  ðược chia sẻ bởi tất cả các ngôn ngữ ñược .NET hỗ trợ  Các lớp trong BCL ñược phân loại, mỗi loại ñược ñịnh nghĩa trong một namespaces riêng C# Simplified / Session 1 / 54 of 45 Các namespaces hay ñược sử dụng nhất Namespace / Class What it contains? System Much of the functionality of the BCL is contained within this namespace. It comprises of various other namespaces within it. System.Array class Contains methods for manipulating arrays. System.Threading Contains classes for Multi-Threading. System.Math class Contains methods for performing mathematical functions. System.IO Contains classes for reading and writing to files and streams. System.Reflection Contains classes for reading metadata from assemblies. System.Net Contains classes for Internet access and socket programming 28 C# Simplified / Session 1 / 55 of 45 System.Array Provides classes and methods for manipulating arrays using System; class Test { static void Main() { int[] arrayToReverse= {1,2,3,4,5,6,7}; Console.WriteLine ("Contents of Array before Reversing:\n"); displayArray (arrayToReverse); Array.Reverse (arrayToReverse); Console.WriteLine("\n\nContents of Array after Reversing:\n"); displayArray (arrayToReverse); } C# Simplified / Session 1 / 56 of 45 System.Array public static void displayArray(Array myArray) { foreach(int arrValue in myArray) { Console.WriteLine (arrValue); } } } 29 C# Simplified / Session 1 / 57 of 45 System.Array – Các phương thức khác C# Simplified / Session 1 / 58 of 45 System.Threading  Sử dụng ñễ cài ñặt xử lý ña luồng  ða luồng (Multi-threading) là thực thi nhiều tiến trình ñồng thời 30 C# Simplified / Session 1 / 59 of 45 System.Threading – Ví dụ using System; using System.Threading; class Test { static void Main() { Thread newThread = new Thread (new ThreadStart (ThreadToRun)); newThread.Start(); threadToRun(); } C# Simplified / Session 1 / 60 of 45 System.Threading static void threadToRun() { for(int count =1; count<10; count++) { Console.WriteLine(“The Thread Number is {0}”,count); } } } 31 C# Simplified / Session 1 / 61 of 45 ðồng bộ các luồng  Sử dụng cơ chế lock (khóa)  Cơ chế lock ñảm bảo tại mỗi thời ñiểm, chỉ có duy nhất một luồng ñược truy cập một phương thức (loại trừ lẫn nhau) C# Simplified / Session 1 / 62 of 45 ðồng bộ các luồng using System; using System.Threading; class Test { static void Main() { Test objTest = new Test(); Thread newThread = new Thread(new ThreadStart(objTest.threadToRun)); newThread.Start(); objTest.threadToRun(); } 32 C# Simplified / Session 1 / 63 of 45 ðồng bộ các luồng - Output void threadToRun() { lock(this) for (int count =1; count<10; count++) { Console.WriteLine (“The Thread Number is {0}”,count); } } } C# Simplified / Session 1 / 64 of 45 System.IO  Cung cấp nhiều lớp cho vào/ra  Các lớp File và Directory sử dụng ñể quản lý thư mục và tệp  Các thao tác bao gồm sao chép (copying), di chuyển (moving), ñổi tên (renaming) và xóa (deleting) các tệp và thư mục 33 C# Simplified / Session 1 / 65 of 45 System.IO using System; using System.IO; class Test { static void Main(string[] args) { DirectoryInfo[] dirInfoArray; FileInfo[] fileInfoArray; DirectoryInfo objDirInfo = new DirectoryInfo("c:\\Program Files"); dirInfoArray = objDirInfo.GetDirectories ("I*"); fileInfoArray= objDirInfo.GetFiles("*.*"); foreach(DirectoryInfo dirInfo in dirInfoArray) { Console.WriteLine (dirInfo); C# Simplified / Session 1 / 66 of 45 Ví dụ - Output foreach (FileInfo fileInfo in fileInfoArray) { Console.WriteLine (fileInfo); } } } } 34 C# Simplified / Session 1 / 67 of 45 System.IO using System; using System.IO; class Test { static void Main (string[] args) { Console.WriteLine (@"Creating' Directory C:\Sample ..."); Directory.CreateDirectory (@"c:\Sample"); DateTime creationDate = Directory.GetCreationTime (@"c:\Sample"); Console.WriteLine ("Directory Created on : " + creationDate.ToString()); } } C# Simplified / Session 1 / 68 of 45 System.IO Các lớp khác 35 C# Simplified / Session 1 / 69 of 45 System.String Class using System; class Test { static void Main(string[] args) { String strOriginal, strToBeReplaced, strToReplace, strReplaced; Console.WriteLine ("Enter a long string :"); strOriginal = Console.ReadLine(); Console.WriteLine ("Enter a string to be replaced in the previous string:"); strToBeReplaced = Console.ReadLine(); Console.WriteLine ("Enter a string to replace the old value :"); Cung cấp các phương thức xử lý xâu C# Simplified / Session 1 / 70 of 45 System.String strToReplace = Console.ReadLine(); strReplaced = strOriginal.Replace(strToBeReplaced,strToReplace); Console.WriteLine ("New String : " + strReplaced); } } 36 C# Simplified / Session 1 / 71 of 45 Các phương thức của String This method identifies the substrings in this instance, that are delimited by one or more characters specified in an array, then places the substrings into a String array. String Split(char[]); String Split (char[], int); Split This method right-aligns the characters in this instance, padding on the left with spaces or a specified Unicode character for a specified total length.. string PadLeft(int); string PadLeft(int, char); PadLeft This method checks whether the end of this instance matches with the specified string. Bool EndsWith (stringValue); EndsWith This method creates a new instance of a string with the same value as a specified string. String Copy(stringStr);Copy ActivitiesSyntaxMethod C# Simplified / Session 1 / 72 of 45 System.Convert  Cung cấp nhiều phương thức chuyển ñổi xâu thành số: ToByte, ToInt16, ToInt32, ToFloat, ToLong, …  Ví dụ: String xau = “1234”; int so = Convert.ToInt32(xau); 37 C# Simplified / Session 1 / 73 of 45 System.Collections (sưu tập)  Collections là các kiểu dữ liệu ñược sử dụng ñể chứa nhiều ñối tượng thuộc nhiều kiểu liệu khác nhau  Lớp Hashtable C# Simplified / Session 1 / 74 of 45 System.Collections – Ví dụ using System.Collections; class HashDemo { static void Main() { Hashtable listOfStudents = new Hashtable(); listOfStudents.Add ("Sam", "8605130"); listOfStudents.Add("Smith", "8604292"); listOfStudents.Add("Tom", "8604292"); System.Console.WriteLine ("The number of students in the school are {0} ", listOfStudents.Count); } } 38 C# Simplified / Session 1 / 75 of 45 ArrayList Class  ArrayList là lớp danh sách, cho phép lưu trữ, quản lý các ñối tượng theo kiểu danh sách C# Simplified / Session 1 / 76 of 45 ArrayList Class Chỉ một phần tử tại một chỉ mục cụ thểItem Kích thước cố ñịnh hay khôngIsFixedSize Chỉ ñọc hay khôngIsReadOnly Số phần tử thực sự ñược lưu trong danh sách Count Số vị trí có thể dùng ñể chứa các phần tửCapacity Mô tảThuộc tính Các thuộc tính 39 C# Simplified / Session 1 / 77 of 45 ArrayList Class Xác ñịnh chỉ mục cuối cùng của phần tử.LastIndexOf Xác ñịnh chỉ mục ñầu tiên của phần tửIndexOf Copy các phần tử sang arrayCopyTo Kiểu tra một phần tử có trong danh sách hay khôngContains Loại bỏ tất cả các phần tử khỏi danh sáchClear Thêm phần tử vào danh sáchAdd DescriptionMethod C# Simplified / Session 1 / 78 of 45 ArrayList Class – Ví dụ using System; using System.Collections; public class ArrlistDemo { public static void Main() { ArrayList myArrLst = new ArrayList(); Console.WriteLine ("Enter names of 5 countries below:"); for(int i = 0;i <= 4;i++) { Console.Write ("Enter country {0} :", i+1); string str1 = Console.ReadLine(); myArrLst.Add(str1); } Console.WriteLine( "Information about Countries" ); 40 C# Simplified / Session 1 / 79 of 45 ArrayList Class - Ví dụ Console.WriteLine( "\tCount:{0}", myArrLst.Count ); Console.WriteLine( "\tCapacity: {0}", myArrLst.Capacity ); Console.WriteLine ("The contents of the arraylist are as follows"); System.Collections.IEnumerator myEnumerator = myArrLst.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "\n{0}", myEnumerator.Current ); Console.ReadLine(); } } C# Simplified / Session 1 / 80 of 45 Xử lý ngoại lệ … Các lớp ngoại lệ 41 C# Simplified / Session 1 / 81 of 45 Try & catch C# Simplified / Session 1 / 82 of 45 Sử dụng nhiều catch 42 C# Simplified / Session 1 / 83 of 45 catch tổng quát C# Simplified / Session 1 / 84 of 45 throw Sử dụng throw ñể phát ra một ngoại lệ tự ñịnh nghĩa 43 C# Simplified / Session 1 / 85 of 45 Finally Mã viết trong finally ñược thực thi bất kể ngoại lệ có phát sinh hay không C# Simplified / Session 1 / 86 of 45 try…..catch – Ví dụ using System; class ExceptionDemo { static void Main() { int dividend = 50; int userInput = 0; int quotient = 0; Console.WriteLine ("Enter a number : "); try { userInput = Convert.ToInt32 (Console.ReadLine()); quotient = divident /userInput; } 44 C# Simplified / Session 1 / 87 of 45 try….catch – Ví dụ catch (System.FormatException excepE) { Console.WriteLine (excepE); } catch (System.DivideByZeroException excepE) { Console.WriteLine ("catch block"); Console.WriteLine (excepE); Console.WriteLine(""); } C# Simplified / Session 1 / 88 of 45 try….catch – Ví dụ finally { Console.WriteLine ("finally block"); if (quotient != 0) { Console.WriteLine("The Integer Quotient of 50 divided by {0} is {1}", userInput, quotient); } } } } 45 C# Simplified / Session 1 / 89 of 45 Thuộc tính (Properties)  Các lớp C# có thể có properties – thuộc tính chỉ ñặc tính hoặc thông tin về ñối tượng.  Properties khác với trường (field)  Có thể dùng properties ñể truy cập các trường – thay cho các phương thức get, set C# Simplified / Session 1 / 90 of 45 Properties { get { } set { } } có thể là private, public, protected hoặc internal. có thể nhận bất kỳ kiểu hợp lệ nào. 46 C# Simplified / Session 1 / 91 of 45 Properties – Get & Set public class Employee { private String sName private String sId public string sId { get { return sId; } set { sId = value } } C# Simplified / Session 1 / 92 of 45 Properties – Ví dụ using System; public class Student { public string sName; //Field private string internal_sId;//Field public string sId //Property { get { return internal_sId; } set { internal_sId = value; } } } 47 C# Simplified / Session 1 / 93 of 45 Properties – Ví dụ class Test { static void Main() { Student one = new Student(); one.sName = "Sam"; one.sId = "St423"; Console.WriteLine("The Name of the Student is {0} and his Id is {1}", one.sName, one.sId); } } C# Simplified / Session 1 / 94 of 45 Properties – Giải thích 48 C# Simplified / Session 1 / 95 of 45 Các loại Properties  Public  Private  Read / Write: có cả hai thao tác get và set.  Read - Only: chỉ có thao tác get.  Write - Only: chỉ có thao tác set. C# Simplified / Session 1 / 96 of 45 Read-only Property – Ví dụ public class Employee { private int empsalary = 15000; //Field public int EmpSalary //Property { get { return empsalary; } } } class EmployeeTest { 49 C# Simplified / Session 1 / 97 of 45 Read-only Property – Ví dụ static void Main() { Employee objEmployee = new Employee(); System.Console.WriteLine ("The salary of the Employee is {0}", objEmployee.EmpSalary); objEmployee.EmpSalary = 25000; //error } } C# Simplified / Session 1 / 98 of 45 Properties Fields  Properties là các trường logic  Properties là mở rộng của fields  Không giống fields, properties không có lưu trữ trực tiếp 50 C# Simplified / Session 1 / 99 of 45 Indexers – Chỉ mục  Indexers là thành phần ñơn giản của C#  ðược tạo cho các mảng ñể có thể truy cập các phần tử thông qua chỉ mục từ một ñối tượng  Cho phép một ñối tượng ñược chỉ mục như một mảng  Cho phép truy cập tới các phần tử của lớp như cách truy cập mảng C# Simplified / Session 1 / 100 of 45 Indexers – Ví dụ class IndexerExample { public string[] stringList =new string[10]; public string this[int index] { get { return stringList[index]; } set { stringList[index] = value.ToString(); } } } 51 C# Simplified / Session 1 / 101 of 45 Indexers - Output class Test { static void Main() { IndexerExample indexTest = new IndexerExample(); indexTest.stringList[1]="Sam"; indexTest[2]="Tom"; System.Console.WriteLine("indexTest[1] is {0}\nindexTest[2] is {1}", indexTest[1], indexTest[2]); } } C# Simplified / Session 1 / 102 of 45 Các bước tạo chỉ mục  Bổ ngữ chỉ phạm vi truy cập  Kiểu của các phần tử  Từ khóa this  Xác ñịnh kiểu dữ liệu của chỉ mục  Các tham số chỉ mục, mỗi tham số có kiểu và tên  Xác ñịnh các truy cập get và set 52 C# Simplified / Session 1 / 103 of 45 Các quy tắc tạo chỉ mục  Chỉ mục phải có ít nhất một tham số  Các tham số phải ñược ñặt giá trị C# Simplified / Session 1 / 104 of 45 Chỉ mục vs. Mảng  Chỉ mục không trỏ tới các ñịa chỉ nhớ  Chỉ mục có thể nhận kiểu khác nguyên  Có thể nạp chồng chỉ mục 53 C# Simplified / Session 1 / 105 of 45 Indexer – Example 1 using System.Collections; class StrIndex { public Hashtable studentList = new Hashtable(); public int this[string name] { get { return (int) studentList[name]; } set { studentList[name] = value; } } } C# Simplified / Session 1 / 106 of 45 Indexer – Example 1 Contd… class Test { static void Main() { StrIndex objIndex = new StrIndex(); objIndex ["Sam"] = 232676; objIndex ["Tom"] = 455464; System.Console.WriteLine ("Phone number of Sam is {0} and Phone number of Tom is {1}", objIndex ["Sam"], objIndex["Tom"]); } } 54 C# Simplified / Session 1 / 107 of 45 Indexer Example - 2 using System.Collections; class IndexerExample { public string[] stringList = new string[10]; public string this[int index] { get { return stringList[index]; } set { stringList[index] = value.ToString(); } } public Hashtable studentList = new Hashtable(); C# Simplified / Session 1 / 108 of 45 Indexer Example – 2 Contd… public int this[string number] { get { return (int) studentList [number]; } set { studentList [number] = value; } } } 55 C# Simplified / Session 1 / 109 of 45 Indexer Example – 2 Contd… class Test { static void Main() { IndexerExample indexTest = new IndexerExample(); indexTest.stringList[1] = "Sam"; indexTest[2] = "Tom"; indexTest ["Sam"] = 232; indexTest ["Tom"] = 455; } } C# Simplified / Session 1 / 110 of 45 Sử dụng nhiều tham số

Các file đính kèm theo tài liệu này:

  • pdfbo_tro_1_mot_so_diem_khac_cua_c_so_voi_c.pdf
Tài liệu liên quan