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

Chương trình C# đơn giản

/* This is the Hello world Program in C# */

using System;

class HelloWorldDemo

{

public static void Main()

{

Console.WriteLine (“This is the Hello

World program”);

}

}

pdf62 trang | Chia sẻ: oanh_nt | Lượt xem: 1548 | Lượt tải: 0download
Bạn đang xem trước 20 trang nội dung tài liệu 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
1Bổ trợ 1 Một số ñiểm khác của C# so với C++ C# Simplified / Session 1 / 2 of 45 Chương trình C# ñơn giản /* This is the Hello world Program in C# */ using System; class HelloWorldDemo { public static void Main() { Console.WriteLine (“This is the Hello World program”); } } 2C# Simplified / Session 1 / 3 of 45 Khai báo biến  AccessModifier DataType Variable Public Private Protected int string float C# Simplified / Session 1 / 4 of 45 Biến trùng tên với từ khóa, sử dụng @ using System; class VariableDemo { public static void Main() { string @string; @string = ”string is a keyword but used as a variable name in this example”; Console.WriteLine (@string); } } 3C# Simplified / Session 1 / 5 of 45 C# cung cấp nhiều kiểu dữ liệu, cả kiểu số rất lớn bool val1 = true; bool val2 = false; Logic bool char val = 'h'; Ký tựchar float val = 1.23F; Thực 64 bitfloat byte val = 12;bytebyte int val = 12; Nguyên 32 bit int string s = “hello”; Xâustring object o = null; Kiểu dữ liệu cơ sởobject Ví dụMô tảKiểu dữ liệu trong C# C# Simplified / Session 1 / 6 of 45 Khai báo mảng  Kiểu[] ten = new Kiểu[số_phần_tử]  Ví dụ:  int[] a = new int[200];  String[] s = new String[20]; 4C# Simplified / Session 1 / 7 of 45 Vào / Ra trong C#  Với ứng dụng bàn giao tiếp (console) Sử dụng ñối tượng System.Console với các phương thức ñọc/ghi hay ñược sử dụng nhất là  Console.ReadLine()  Console.WriteLine() C# Simplified / Session 1 / 8 of 45 {i}, i = 0, 1, … trong xâu ký tự tham số thứ nhất ñược gọi là giành chỗ. Ký tự giành chỗ {i} sẽ ñược thay thế bởi giá trị của tham số thứ i trong danh sách khi in. Vào / Ra trong C# - Ví dụ using System; class TestDefaultValues { static void Main() { int number, result; number=5; result=100 * number; Console.WriteLine (“Result is {0} when 100 is multiplied by number {1}”, result, number); } } 5C# Simplified / Session 1 / 9 of 45 Cấu trúc ñiều khiển switch cho phép sử dụng bất kỳ giá trị gì ñể làm giá trị so sánh switch(thXuly) { case “NGHI_HOC”: Console.Write(“Ban da nghi hoc”); break; case “DI_HOC_MUON”: Console.Write(“Ban di hoc muon”); break; default: Console.Write(“Ban di hoc rat tot”); break; } Giá trị so sánh với các case trong ví dụ này là xâu ký tự C# Simplified / Session 1 / 10 of 45 Lệnh lặp foreach (1)  Sử dụng ñể lặp và duyệt các phần tử trong collection hoặc array  Cú pháp - 6C# Simplified / Session 1 / 11 of 45 Lệnh lặp foreach – Ví dụ using System; public class ForEachDemo { static void Main (String[] args) { int index; String[] array1 = new String[3]; for (index=0; index<3; index++) { array1[index] = args [index]; } foreach (String strName in array1) { Console.WriteLine(strName); } } } C# Simplified / Session 1 / 12 of 45 Hai kiểu dữ liệu trong C#  Kiểu giá trị - int, char , and structures - Kiểu tham chiếu - classes, interfaces, arrays and strings 7C# Simplified / Session 1 / 13 of 45  Dùng ñể lưu giá trị  Are stored in a stack  Dùng ñể lưu ñịa chỉ (tham chiếu) của ñối tượng  = null nghĩa là không tham chiếu ñến ñối tượng nào cả Hai kiểu dữ liệu trong C# Value Types Reference Types C# Simplified / Session 1 / 14 of 45 Value Types using System; class DataTypeTest { public static void Main() { int variableVal = 100; funcTest(variableVal); Console.WriteLine(“This value of the variable is {0}",variableVal); } static void funcTest (int variableVal) { int tempVar = 10; variableVal = tempVar*20; } } 8C# Simplified / Session 1 / 15 of 45 Reference Types using System; class DataTypeTest { public int variableVal; } class DataTypeTestRef { static void Main() { DataTypeTest dataTest = new DataTypeTest(); dataTest.variableVal = 100; funcDataTypeTest(dataTest); Console.WriteLine (dataTest.variableVal); } C# Simplified / Session 1 / 16 of 45 Reference Types - Contd static void funcDataTypeTest(DataTypeTest dataTest) { int tempVar = 10; dataTest.variableVal = tempVar*20; } } 9C# Simplified / Session 1 / 17 of 45 C# sử dụng biến tham chiếu ref hoặc biến ra out thay cho con trỏ ñể thống nhất cách xử lý và an toàn khi sử dụng public void ham1(int vao, ref int vaora, out int ra) { ra = vao + vaora; vaora = vao – vaora; } int x = 10, y = 6, z; ham1(x, ref y, out z); Kết quả: x = 10 y = 4 z = 16 C# Simplified / Session 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

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