Bài giảng Lập trình Windows - Chương 2: Ngôn ngữ C#

Cấu trúc chương trình C# Kiểu dữ liệu, từ khoá, định danh biến, hằng… Chuyển đổi kiểu Console I/O Tham số ref, out, param Lệnh phân nhánh switch, lệnh nhảy Lệnh lặp for, while, do while, foreach Mảng 1 chiều, đa chiều Kiểu enumeration

ppt123 trang | Chia sẻ: candy98 | Lượt xem: 428 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Bài giảng Lập trình Windows - Chương 2: Ngôn ngữ C#, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Ngôn ngữ C#ContentCấu trúc chương trình C#Kiểu dữ liệu, từ khoá, định danh biến, hằngChuyển đổi kiểuConsole I/OTham số ref, out, paramLệnh phân nhánh switch, lệnh nhảy Lệnh lặp for, while, do while, foreachMảng 1 chiều, đa chiềuKiểu enumeration2Cấu trúc chương trình C#3using namespace { [Khóa truy xuất] class { public static void Main() { }// thành viên khác }// lớp khác *.csCấu trúc chương trình C#using: làm code gọn hơn, không cần phải dùng tên của namspaceusing System.namespace của chương trình: ko bắt buộc. Dùng để hạn chế phạm vi của một tên, làm cho tên này chỉ có ý nghĩa trong vùng đã định nghĩa.Giả sử có một người nói Tùng là một kỹ sư, từ kỹ sư phải đi kèm với một lĩnh vực nhất định nào đó, vì nếu không thì chúng ta sẽ không biết được là anh ta là kỹ sư cầu đường, cơ khí hay phần mềm. Khi đó một lập trình viên C# sẽ bảo rằng Tùng là CauDuong.KySu phân biệt với CoKhi.KySu hay hanMem.KySu. Namespace trong trường hợp này là CauDuong, CoKhi, PhanMem sẽ hạn chế phạm vi của những từ theo sau.4Cấu trúc chương trình C#Nếu ko có namespace  namespace mặc định ko tênNamespace có thể chứa: struct, interface, delegate, enumTrường hợp đơn giản nhất: 1 lớp, 1 file cs và namespace mặc định5Cấu trúc chương trình C#class: kiểu trong C# được định nghĩa là một lớp (class), và các thể hiện riêng của từng lớp được gọi là đối tượng (object). Tối thiểu có 1 lớp chứa hàm entry point Main của chương trình.Phương thức chính là các hàm được định nghĩa trong lớp. Các phương thức này chỉ ra rằng các hành động mà lớp có thể làm được cùng với cách thức làm hành động đó. public static void Main(): đầu vào của lớp (entry point) và được CRL gọi đầu tiên khi thực thi. 6Data TypeBao gồmLớp đối tượng objectký tự charChuỗi stringSố nguyên có dấu sbyte, short, int, long Số nguyên không dấu byte, ushort, uint, ulongSố thực float, double, decimalKiểu logic boolAlias của các lớp dữ liệu trong .NETstring System.Stringint System.Int32object System.Object7Data TypeSử dụng kiểu dữ liệuĐịnh nghĩa trước (C#)Built-in : int, long, string, objectChương trình định nghĩaClass, struct, enumPerson, Student, Employee8Data TypeBuilt-inUser definedThe built-in value typeNameCTS TypeSizeRangesbyteSystem.SByte 8-128..127shortSystem.Int1616 (-32768 .. 32767)intSytem. Int3232-231..231-1longSytem. Int6464-263..263-1byteSystem.SByte 80..255ushortSystem.UInt1616 (0 .. 65535)uintSystem.UInt3232 0..232-1ulongSystem.UInt64640..264-1floatSystem.Single32xấp xỉ từ 3,4E - 38 đến 3,4E+38doubleSystem.Double641,7E-308 đến 1,7E+308decimalSystem.Decimal128Có độ chính xác đến 28 con sốboolSystem.Boolean Kiểu true/falsecharSystem.Char16Ký tự unicode9The built-in reference typeobject: Sytem.ObjectKiểu dữ liệu gốc, cha của tất cả các kiểu dữ liệu trong C#object o = new object();string: Sytem.StringChuỗi ký tự Unicodestring s1 = “Hi”;string s2 = “Hi Hi “;string s = s1 + s2;10The built-in reference type11Phân loại kiểu dữ liệu12Value typeReference typeData typeint num;long count;Object obj = new Object();String str = “reference type”;Phân loại theo cách thức lưu trữ dữ liệuValue TypeChứa giá trị trực tiếpKhông thể nullPhải chứa giá trị xác địnhBao gồmPrimitive typedouble, char, int, floatEnumstruct13int i = 59;59i7.83x59adouble x = 7.83;int a = i;Reference typeChỉ tới nơi chứa dữ liệuCó thể nullnull: không chỉ tới bất kỳ đâuBao gồmLớp (class) string, objectGiao diện (interface)Mảng (array)Đại diện (delegate)14string s1 = "Hello";"Hello""Bye"s2s3s1string s2 = "Bye";string s3;s3 = s1;Value type vs. Reference typeCharacteristicValue typeReference typeVariable holdValueReferenceAllocatedStackHeapDefaultZeroNullParameterCopy valueCopy reference15identifierĐịnh danh: những từ được đặt ra để đại diện cho mọi thứ dùng trong chương trìnhKhi đặt định danh: nên có tính gợi nhớTạo ra định danh mớiHelloWorld, Program, Perform, phải khai báo trước khi sử dụngDùng định danh có sẵnConsole, WriteLine, ReadLine, phải chỉ ra nơi chứa định danh (namespace)16IdentifierBao gồm chữ cái, chữ số, ký tự gạch dướiKhông được bắt đầu bằng chữ sốChuong_Trinh, x25, z, _abc, XửLý  hợp lệ2abc, Chuong-Trinh, Xu Ly, class  không hợp lệPhân biệt CHỮ HOA và chữ thườngChuongTrinh và chuongtrinh là khác nhauCác định danh được khai báo trong cùng phạm vi (scope) không được trùng nhauPhải khác với từ khóa (dùng “@” khắc phục)17Keyword18ConstantMột hằng là một biến nhưng trị không thay đổi const int a = 100; // giá trị ko thể thay đổiHằng bắt buộc phải được gán giá trị lúc khai báo Trị của hằng có thể được tính toán vào lúc biên dịch Hằng bao giờ cũng static 19ConstantƯu điểmChương trình dễ đọc, khắc phục những con số “magic number” trong code.Chương trình dễ sửa hơn.Tránh lỗi dễ dàng hơn, trình biên dịch sẽ báo lỗi nếu gán lại giá trị cho hằng20Minh họa sử dụng hằng21Định nghĩa hằngConstantreadonly22const: phải được gán giá trị khi khai báoreadonly: ko cần khởi tạo trước, khi gán giá trị thì sau đó ko thay đổi đượcChưa được khởi gánKo được thay đổiVariableBiến là nơi lưu dữ liệu của chương trìnhDữ liệu của biếnNằm trong bộ nhớ vật lý (physical RAM)Có thể thay đổi giá trịPhải khai báo trước khi dùngIdentifier: tên để đại diện cho biếnData type: dạng lưu trữ dữ liệu của biến23Data type identifierVariablePhạm vi (scope)Được xác định bởi cặp dấu { và }Có thể chứa phạm vi nhỏ hơnVị trí khai báo biếnTrong thân phương thức: biến cục bộTrong thân lớp(trong class): thuộc tínhBiến trong C# chỉ có tác dụng trong phạm vi mà nó được khai báo24KeywordDescriptionPublicTruy xuất từ bất cứ nơi nào trong chương trình hay từ bất cứ chương trình khác mà tham khảo tới nó.PrivateTruy xuất từ bất cứ nơi nào trong lớp chứa nó.ProtectedTruy xuất từ bất cứ nơi nào trong lớp chứa nó hay bất cứ lớp nào thừa kế từ lớp này.PrefixData TypeblnBooleandatDatedecDecimaldblDouble-precisionintIntegerlngLong IntegersngSingle-precisionstrStringVariablesNguyên tắc đặt tên biếnstring strName, strSSN ; int intAge; decimal decPayRate ; decimal decTax=0.1 ; bool blnInsured ; long lngPopulation ; decimal decDT, decCD, decCR;decimal decHour, decSumSal, decDiemTB, decSum=0;decimal decTAX = 0.12, decHSLUONG=3.16;Const decimal decDISCOUNT_RATE = 0.15M;Note: Constants are named using all uppercase letters EXCEPT the prefix.VariablesType castÉp kiểu: chuyển giá trị từ kiểu này sang kiểu khácVí dụChuyển từ int qua float và ngược lạiCó hai loạiÉp kiểu ngầm định (implicit type-cast)Ép kiểu chỉ định (explicit type-cast)27Implicit type castDo C# tự thực hiệnKhông cần lập trình viên can thiệpXảy ra khiÉp từ kiểu nhỏ qua kiểu lớnÉp từ lớp dẫn xuất qua lớp cơ sở28int i = 59;double x = i;string s = "Hello";object o = s;Implicit type-castFromTosbyte short, int, long, float, double, decimal byte short, ushort, int, uint, long, ulong, float, double, decimal short int, long, float, double, decimal ushort int, uint, long, ulong, float, double, decimal int long, float, double, decimal uint long, ulong, float, double, decimal long, ulong float, double, decimal float double char ushort, int, uint, long, ulong, float, double, decimal 29Explicit type-castDo lập trình viên chỉ địnhXảy ra khiÉp từ kiểu lớn qua kiểu nhỏ: có thể mất giá trịÉp từ lớp cơ sở qua lớp dẫn xuất30double x = 74.86;int i = (int)x; // i = 74string s = "Hello";object o = s;string s2 = (string)o;Using Convert classThường dùng khi cần chuyển đổi giữa các kiểu không có liên hệ với nhauConvert.toDataType(SourceValue)Ví dụ: chuyển từ chuỗi sang số thực31string s1 = "56.8";double x = Convert.ToDouble(s1); // x = 56.8int i = Convert.ToInt32(s2); // i = 95string s2 = "95";byte j = Convert.ToByte(x); // j = 56, ít dùngConsole I/OĐể đọc ký tự văn bản từ cửa sổ consoleConsole.Read() giá trị trả về là intConsole.ReadLine() giá trị trả về là stringĐể xuất chuỗi ký tự dùngConsole.Write() / Console.WriteLine()32Console I/O33Console I/OConsole.WriteLine()34\n: ký tự xuống dòngConsole I/O35/ F5Xuất chuỗiĐọc chuỗiChờ đọc 1 dòng, mục đích là dừng màn hìnhAddition.cs1 // Fig. 3.11: Addition.cs2 // An addition program.3 using System;4 class Addition5 {6 static void Main( string[] args )7 {8 string firstNumber, // first string entered by user9 secondNumber; // second string entered by user10 int number1, // first number to add11 number2, // second number to add12 sum; // sum of number1 and number213 // prompt for and read first number from user as string14 Console.Write( "Please enter the first integer: " );15 firstNumber = Console.ReadLine();16 // read second number from user as string17 Console.Write( "\nPlease enter the second integer: " );18 secondNumber = Console.ReadLine();19 // convert numbers from type string to type int20 number1 = Int32.Parse( firstNumber );21 number2 = Int32.Parse( secondNumber );22 // add numbers23 sum = number1 + number2; Addition.csConsole I/OPlease enter the first integer: 45 Please enter the second integer: 72 The sum is 117.32 // display results33 Console.WriteLine( "\nThe sum is {0}.", sum );34 35 } // end method Main36 37 } // end class AdditionConsole I/OBoxing & UnboxingKiểu giá trị có thể được chuyển thành kiểu đối tượngBoxingUnboxing 38UnboxingBoxingchecked & unchecked39throws OverFlowExceptionOperatorsArithmetic OperationsRelational OperatorsAssignment OperatorsIncrement and Decrement OperatorsLogical and Conditional OperatorsArithmetic OperationsNotes: Must be written in a straight lineThere are no exponentsDivision can vary depending on the variables usedWhen dividing two integers the result is always rounded down to an integer. To be more exact use a variable that supports decimalsOperatorOperationExample+Addition3+7 = 10-Subtraction 3-7 = -4*Multiplication 2*3 = 6, 2*2 =4/Division 9/3 = 3, 10/3 =3%Modulus (division's remainder) 9%2 =1 Arithmetic OperationsArithmetic OperationsThứ tự thực hiệnArithmetic OperationsFig. 3.17 Order in which a second-degree polynomial is evaluated. Step 1.Step 2.Step 5.Step 3.Step 4.Step 6.y = 2 * 5 * 5 + 3 * 5 + 7;2 * 5 is 10 (Leftmost multiplication)y = 10 * 5 + 3 * 5 + 7;10 * 5 is 50 (Leftmost multiplication)y = 50 + 3 * 5 + 7;3 * 5 is 15 (Multiplication before addition)y = 50 + 15 + 7;50 + 15 is 65 (Leftmost addition)y = 65 + 7;65 + 7 is 72 (Last addition)y = 72; (Last operation—place 72 into y)Relational OperatorsComparison.cs1 // Fig. 3.19: Comparison.cs2 // Using if statements, relational operators and equality3 // operators.4 5 using System;6 7 class Comparison8 {9 static void Main( string[] args )10 {11 int number1, // first number to compare12 number2; // second number to compare13 14 // read in first number from user15 Console.Write( "Please enter first integer: " );16 number1 = Int32.Parse( Console.ReadLine() );17 18 // read in second number from user19 Console.Write( "\nPlease enter second integer: " );20 number2 = Int32.Parse( Console.ReadLine() );21 22 if ( number1 == number2 )23 Console.WriteLine( number1 + " == " + number2 );24 25 if ( number1 != number2 )26 Console.WriteLine( number1 + " != " + number2 );27 28 if ( number1 number2 )32 Console.WriteLine( number1 + " > " + number2 );33 Relational OperatorsRelational OperatorsPlease enter first integer: 2000 Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000Please enter first integer: 1000 Please enter second integer: 20001000 != 20001000 = 100034 if ( number1 = number2 )38 Console.WriteLine( number1 + " >= " + number2 );39 40 } // end method Main41 42 } // end class ComparisonRelational OperatorsCompound Assignment OperatorsAssignment operatorsCan reduce codex += 2 is the same as x = x + 2Can be done with all the math operators++, -=, *=, /=, and %=Assignment OperatorsIncrement and Decrement OperatorsIncrement operatorUsed to add one to the variablex++Same as x = x + 1Decrement operatorUsed to subtract 1 from the variabley--Pre-increment vs. post-incrementx++ or x--Will perform an action and then add to or subtract one from the value++x or --xWill add to or subtract one from the value and then perform an actionIncrement and Decrement Operators Ví dụ: i=3, j=15;Increment.csint c; c = 5;Console.WriteLine( c ); Console.WriteLine( c++ ); Console.WriteLine( c ); Console.WriteLine(); c = 5;Console.WriteLine( c ); Console.WriteLine( ++c ); Console.WriteLine( c ); 556 566 Increment and Decrement OperatorsLogical and Conditional OperatorsOperatorsLogical AND (&)Conditional AND (&&)Logical OR (|)Conditional OR (||)Logical exclusive OR or XOR (^)Logical NOT (!)Can be avoided if desired by using other conditional operatorsUsed to add multiple conditions to a statementLogical and Conditional Operators Logical and Conditional OperatorsStructured Programming SummaryLogicalOperators.cs1 // Fig. 5.20: LogicalOperators.cs2 // Demonstrating the logical operators.3 using System;4 5 class LogicalOperators6 {7 // main entry point for application8 static void Main( string[] args )9 {10 // testing the conditional AND operator (&&)11 Console.WriteLine( "Conditional AND (&&)" +12 "\nfalse && false: " + ( false && false ) +13 "\nfalse && true: " + ( false && true ) +14 "\ntrue && false: " + ( true && false ) +15 "\ntrue && true: " + ( true && true ) );16 17 // testing the conditional OR operator (||)18 Console.WriteLine( "\n\nConditional OR (||)" +19 "\nfalse || false: " + ( false || false ) +20 "\nfalse || true: " + ( false || true ) +21 "\ntrue || false: " + ( true || false ) +22 "\ntrue || true: " + ( true || true ) );23 24 // testing the logical AND operator (&)25 Console.WriteLine( "\n\nLogical AND (&)" +26 "\nfalse & false: " + ( false & false ) +27 "\nfalse & true: " + ( false & true ) +28 "\ntrue & false: " + ( true & false ) +29 "\ntrue & true: " + ( true & true ) );30 Only true if both inputs are trueOnly false if both inputs are falseThe result is only true if both are trueOutputs a truth table for the conditional AND operator (&&)Outputs a truth table for the conditional OR operator (||)Outputs a truth table for the logical AND operator (&)LogicalOperators.cs Program Output31 // testing the logical OR operator (|)32 Console.WriteLine( "\n\nLogical OR (|)" +33 "\nfalse | false: " + ( false | false ) +34 "\nfalse | true: " + ( false | true ) +35 "\ntrue | false: " + ( true | false ) +36 "\ntrue | true: " + ( true | true ) );37 38 // testing the logical exclusive OR operator (^)39 Console.WriteLine( "\n\nLogical exclusive OR (^)" +40 "\nfalse ^ false: " + ( false ^ false ) +41 "\nfalse ^ true: " + ( false ^ true ) +42 "\ntrue ^ false: " + ( true ^ false ) +43 "\ntrue ^ true: " + ( true ^ true ) );44 45 // testing the logical NOT operator (!)46 Console.WriteLine( "\n\nLogical NOT (!)" +47 "\n!false: " + ( !false ) +48 "\n!true: " + ( !true ) );49 }50 }Conditional AND (&&)false && false: Falsefalse && true: Falsetrue && false: Falsetrue && true: TrueConditional OR (||)false || false: Falsefalse || true: Truetrue || false: Truetrue || true: TrueReturns the opposite as the inputReturns false when the two conditionals are the sameIf one is true the result is trueOutputs a truth table for the logical OR operator (||)Outputs a truth table for the logical exclusive OR operator (||)Outputs a truth table for the logical NOT operator (!)LogicalOperators.cs Program OutputLogical AND (&)false & false: Falsefalse & true: Falsetrue & false: Falsetrue & true: True  Logical OR (|)false | false: Falsefalse | true: Truetrue | false: Truetrue | true: True  Logical exclusive OR (^)false ^ false: Falsefalse ^ true: Truetrue ^ false: Truetrue ^ true: False  Logical NOT (!)!false: True!true: FalseLogical and Conditional OperatorsControl Structuresadd grade to totaladd 1 to countertotal = total + grade;counter = counter + 1;Fig. 5.1 Flowcharting C#’s sequence structure.1. Cấu trúc tuần tựif Selection StructureThe if structureCác phát biểuBiểu thức điều kiệntruefalseFig. 5.3 Flowcharting a single-selection if structure.if/else selection structureConditionsdo somethingdo something elsefalsetrueFig. 5.4 Flowcharting a double-selection if/else structure.if/else selection structureusing System;using System.Collections.Generic;using System.Text;namespace IfElse{ class Program { static void Main(string[] args) { int num = 6; string msg = ""; if (num = 60 ? "Passed" : "Failed" ); switch Multiple-Selection Structureswitch Multiple-Selection Structurebreak;case: acase a action(s)truefalse...break;case b action(s)break;falsefalsecase: zcase z action(s)break;default action(s)truetruecase: bswitch Multiple-Selection Structureswitch(weekday){ case 1: Console.WriteLine (“You have selected Monday”); break; case 2: Console.WriteLine (“You have selected Tuesday”); break; default: Console.WriteLine (“Sunday is the Default choice!”); break;}Ví dụ 1LoopsCác loại vòng lặp The While LoopThe Do LoopThe For LoopThe foreach Looptruefalsedo somethingconditionsFig. 4.5 Flowcharting the while repetition structure.LoopTương tự như C: while, do while, for71Phải là giá trị bool: true, falsewhile { // phần thân while}do { // phần thân do while} while ;for( khởi tạo biến lặp; ; thay đổi biến lặp) { // phần thân for}Loop72index = 10;while (index != 0){ Console.WriteLine(index); index--;}index = 0;do{ Console.WriteLine("Happens at least once"); }while (index .(tham số) nếu trong cùng class thì có thể bỏ class NameVí dụ:private void btnNhan_Click(object sender, EventArgs e) { int intA; double dblB; intA = Convert.ToInt32(txtSoA.Text); dblB= Convert.ToDouble(txtSoB.Text); lblKQ.Text = HamTich(intA, dblB).ToString(); } double HamTich(int A, Double dblB) { // lenh cua ham return (A * dblB); }Calling Method User-defined method Maximumpublic double Maximum( double x, double y, double z ){ double maximumValue = x; if ( y > maximumValue ) maximumValue = y; if ( z > maximumValue ) maximumValue = z; return maximumValue; } // end method MaximumUser-defined method Maximumpublic void DetermineMaximum(){ Console.WriteLine( "Enter three floating-point values,\n" + " pressing 'Enter' after each one: " ); double number1 = Convert.ToDouble( Console.ReadLine() ); double number2 = Convert.ToDouble( Console.ReadLine() ); double number3 = Convert.ToDouble( Console.ReadLine() ); double result = Maximum( number1, number2, number3 ); Console.WriteLine( "Maximum is: " + result ); } // end method DetermineMaximum Passing ArgumentsPassing by valueSend a method a copy of the objectWhen returned are always returned by valueSet by value by defaultPassing by referenceSend a method the actual reference pointCauses the variable to be changed throughout the programWhen returned are always returned by referenceThe ref keyword specifies by referenceThe out keyword means a called method will initialize itref, out, paramref: tương tự như truyền tham chiếu trong C/C++Từ khoá ref phải được dùng lúc gọi hàmCác tham số truyền dạng ref phải được khởi tạo giá trị trước 83Khai báo ref trước kiểu dữ liệusử dụng ref cho tham số khi gọi hàmReference and value parameters void SquareRef( ref int x ){ x = x * x; } void Square( int x ){ x = x * x; } Original value of x: 5 Value of x after SquareRef: 25 Value of x after Square: 5 ref, out, paramout: tương tự như refKhác ref là ko cần khởi tạo giá trị trước khi truyền85Khai báo cho tham sốDùng trước tham số khi gọi hàmref, out, param863 phần tử6 phần tửMảng arrayLuôn khai báo ở cuối danh sách tham số Value Typesusing 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;    } }Reference Typesusing System;class DataTypeTest{ public int variableVal;}class DataTypeTestRef{ static void Main() { DataTypeTest dataTest = new DataTypeTest(); dataTest.variableVal = 100; funcDataTypeTest(dataTest); Console.WriteLine (dataTest.variableVal); } Reference Types - Contdstatic void funcDataTypeTest(DataTypeTest dataTest) { int tempVar = 10;       dataTest.variableVal = tempVar*20; }}Value types vs. Reference typesValueReferenceVariable HoldsActual ValueReferenceAllocatedInline (Stack)HeapDefau
Tài liệu liên quan