============================================================================================================================================================================================================= ===============================
??? C # tutorial reading notes Author: plzw Date: 2004-3-2 --2004-3-15 =========================== ============================================================================================================================================================================================================= === Directory ============================================== =========================================== (1) C # and .NET Platform Overview (2) C # language (three ) Conclusion ================================================ ==================================================== ============================================================================================================================================================================================================= ============= (1) C # and .NET Platform Overview ====
============================================================================================================================================================================================================= =========================================================================================================================================================================================================================================================================================== "Support for various user terminals" means that our terminal is not necessarily a PC, which can be PDA or even mobile phones or more advanced terminals. 2. C # is a development language that is tailored to the .NET platform, with the highest efficiency under the .NET platform. 3. In the object-oriented, C # abandoned the C language pointer, but in some cases, you can also write some non-secure code. In this case you can still use the pointer, C # provides an alternative pointer - - Delegates, and C # and Delphi are single inheritance, one class only one base class, which uses interfaces like Delphi to replace multiple inheritance. 4. In Web development, C # and web better integration, XML data can be directly mapped into C # structure, which makes web development more effective and fast. 5. C # uses the GC provided by the .NET Platform to be responsible for the release of resources, using the same exception handling concept as Delphi in C #. 6. The cross-language feature of .NET Platform is provided by its VOS (Virtual OS), VOS supports both process-oriented languages, which provide a type of rich system to accommodate all languages supported. characteristic. 7. When you use a programming language, compile it to IL and META DATA by the corresponding compiler, compile the program when running the program, and then execute. 8. The book says Compiler compiles Source Code into IL instead of direct compilation to the purpose of the local code is to efficiency: almost only part of the features in large applications, such as the efficiency of compilation while performing comparison Compiled high. This explanation does not seem to be quite reasonable. 9. An analysis of a simple C # Console code: // Reference Namespace, similar to USES in Delphi, if you do not quote Namespace, then the 10-12 line // code must be changed to:
// 10? System.console.writeLine ("Please enter your name: / n");
// 11? S = system.console.readline (); // 12? System.console.writeline ("Hello" S "/ N");
1? Using system; // Declaration Namespace Hello
2? Namespace Hello
3? {// Declare a class Hello
4? Class Hello5? {6?? [Stathread] // main method is the entry of the program
7?? Static void main (String [] args) 8?? {9??? Console.writeline ("please enter your name: / n"); 11?? ? s = console.readline (); 12??? console.writeline ("Hello" S "/ N"); // This sentence code can also be written like this, similar to the format function in delphi : // 12??? Console.writeLine ("Hello {0} / n", s);
13??} 14?} 15?} 10. If you do not have VS.NET IDE, we should use CSC to compile and execute programs, CSC support compilation options, for details, please refer to C # Online Help. 11. C # in single line notes for //, multi-line annotations for / * ... * /. ============================================================================================================================================================================================================= ============================== (b) c # language =========================================================================================================================================================================================== ============================================================================================================================================================================================================= ================= Data type:? (1) Simple type? A. Integer (Sbyte, Byte, SHORT, ULONG)?? In the range of the value of the value of the value of C # online help.? Boolene? In C / C , all non-zero integer values are treated as TRUE, while in C # does not exist like this. ? c. Characters ?? d. real shape (float, double)? C # provides a high-precision 128-bit decimal type, similar to currency in delphi, the following is a declarative example:? decimal value = 1.0m • The following standard M indicates that this is a decimal type, otherwise Compiler will be automatically treated as a Double type before assignment. ? (2) Structural? C # has a structure similar to Delphi Record? Struct Phonebook {? PUBLIC STRING NAME; PUBLIC STRUCT Address {? // can use the structure type as another structure the member of
PUBLIC STRING CITY;? PUBLIC STRING STREET;? PUBLIC UINT NO;?}?}? PhoneBook PB; ?? (3) Enumeration Type? Like Delphi, C # support enumeration type? ENUM WeekDay? Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday?} ;? Weekday day ;? Enumeration Type Usually the first element corresponds to 0, the next increment 1, but can also customize the INT value corresponding to the first element: ENUM Weekday? Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday?}; ?? (4). Reference Type? a. Class? • OO-based polymorphism base class system.object can be assigned Any value. ? b. Entrust? This is something used to replace the pointer in C #! If you want to use this stuff, you must also declare this program is unsafe. Declare a commission to indicate the type of principal to the prototype. DELEGATE INT MyDelegate () ;?? The following example is given:????????? pUBLIC INT instancethod ()? {? public int instancethod ()? {? Console.writeline ("Call the instance method.");? Return 0;?} ?? static public int stat staticMethod ()? {? Console.writeline ("Call the static instance method.");? Return 0 ;?}??}?? PUBLIC CLASS TEST? {? Static public void main ()? {? Myclass obj = new myclass () ;?? // will delegate non-static methods?? Mydlegate d = New mydlegate (Obj.instanceMethod) ;?? // Call non-static method
? d () ;?? // will delegate the static method
? d = new mydlegate (myclass.staticMethod);? // Call static method
? d () ;?}??}? c. Array? First look at an example of an array:?????????? {? static void main ()? {?? int [ ] arr = new int [5] ;?? for (int i = 0; i
?? arr [i] = i * i;
??
FOR
INT i = 0; I
??? Console.writeline
"Arr [{0}] = {1}", I, Arr [i]);
?
?
• The above example is very understandable, see the complicated point, the declaration of multi-dimensional array:
??
Class test
??? {
?
Static
void main ()
? {
??
String [] A1;?
// One-dimensional string array
?? String [,] a2;? // two-dimensional string array
?? String [,,] a3;? // 3D string array
?? String [] [] j1;? // Variable group
?? String [] [] [] [] j2; // multi-dimensional variable group
}??}?? The array and declared variables can be assigned the initial value:? USING SYSTEM;? Class Test? {? Static void main ()? {?? Int [] a1 = new int int int INT [] {1, 2, 3} ;? INT [,] a2 = new int [] {{1, 2, 3}, {4, 5, 6}} ;? int [,,] a3 = New Int [10, 20, 30] ;? int [] [] j1 = new int = in t [0] = new int "j1 [0] = new int [] {1, 2, 3} ;?? 1] = new int [] {1, 2, 3, 4, 5, 6} ;?? J1 [2] = new int {1, 2, 3, 4, 5, 6, 7, 8}; ?}??}? When the array is initialized, you must specify the type of array. The following is wrong:??????????????????? {? Static void foo (int [] arg)? { ?}? static void main ()? {?? foo ({1, 2, 3});? // error ??? foo (new int in in {1, 2, 3});? // correct
?}??} 2. Boxing means implicitly converting a value type into an object type. Unboxing refers to explicitly convert an Object type into a value type. 3. The variable naming of C # is allowed to start with @, but this and some of the other languages have conflicts, so it is not recommended to name this. 4. There are seven variable types in C #: • Static variables? (2) Non-static variables (INSTANCE VARIABLES)? The difference between static variables and non-static variables is that static variables belong to classes Non-static variables are class instances. (3) Array Elements? When the array element passes the parameters, the params keyword should be used and can only be one-dimensional array. The following example is given:? Using system;? Public class test? {? Static void foo (params int [] args? {?? Console.writeline ("Array Contains {0} Elements", args.length);? ??? console.writeline ("{0}", i) ;?} ?? public static void main ()? {? int [] arr = new int [5] ;? ? for (int i = 0; i <5; i )?? arr [i] = i * 2 ;?? foo (arr);? // equivalent to foo (new int intelect "{8, 6 , 4, 2});
?? Foo (8, 6, 4, 2);? // Is equivalent to foo (new int in in {});
?? Foo ();?}?}? (4) Value parameters? Do a copy of the value of the parameters, then pass the copy to the function, any operation made in the function is done to the copy, Do not change the original value. (5) Reference parameters (Reference Parameters)? Pass the address of the parameter to the function, any operation made in the function will change the original value. Similar to parameters transmitted using a VAR keyword in Delphi. The following example is given: • Using system;? Public class test? {? Static void foo (Ref Int A, ref Int b)? {?? A = 0 ;?? B = 1;?} ?? public static void Main ()? {?? Int x = 10, y = 10 ;?? Foo (Ref x, ref y);? Console.writeLine ("x = {0} / type = {1}", x, y );?}?}? (6) Output parameters? The output parameter and the reference parameters differ in that the output parameters do not need to initialize the parameters. The following example is given below: • Using system; pUBLIC CLASS TEST? {? Static void foo (Out Int A, OUT INT B)? {? A = 0 ;?? B = 1 ;?} ?? Public static void main ()? {? Int x, y ;?? foo (out x, out y);? console.writeLine ("x = {0} / type = {1}", x, y) ;?}?}? (7) Local variables? Please see the example below:? Class a? {? Public static int x;??? // Static variable? Int y;???? ?? // Non-static variable
? // v: array element A: Value parameter B: Quote Parameter C: Output parameters
? Void foo (int [] = 1;??? // Local variable
?? C = a b ;?}?} 5. C # declaration constant is also using const keywords, but there are some small differences with Delphi, and the constant declaration format in C # is as follows: • Attributes constant-modifiers const type constant -Declarators? constant-modifiers can be one of the New Public Protected InterNal Private. 6. C # supports the ternary operator?, The ternary operator is higher than if the IF condition sentence is more efficient. 7. About i and I have always been the easiest confusion of beginners, just remember, except = and?: Other operators of C # are left in the case. Below is a most typical example help understand:? Using system;? Public class test? {? Static void main ()? {?? Int i?? I = 0 ;?? Console.writeline ("i = {0 } ", i );? console.writeLine (" i = 0} ", i);?? = 0 ;?? console.writeline (" i = {0} ", i); • console.writeline ("i = {0}", i);??? Console.readline ();?}?} • The output of the program is:? I = 0? I = 1? i = 1? I = 18. New operator is used to create an instance of classes, arrays, delegates. 9. TypeOf operator is used to return the type of system object. 10. Checked and Unchecked operators are used to check if the expression is overflow. If you use Checked, when the expression overflows, the abnormality is thrown during the compile period, using unchecked, will not throw an exception, return more than 32-bit . Here is an example using Checked and Unchecked: • Using system; public class test? {? Static int x = 1000000;? Static int y = 1000000;? Public static void main ()? {?? // will be compiled Throw out OverflowException?? Console.writeLine (Checked (x * y));?? // will output -727379968
?? Console.writeline (unchecked (x * y));?}?} • If you do not use CHECKED, you don't use the unchecked keyword, then the result of the output depends on the compilation environment. 11. C # Use the Switch statement to traverse the Case tag, that is, each case statement is jumped with BREAK or GOTO, otherwise the compilation error will be generated. If you really need traversal, you can use the goto statement to jump to the next Case tag. 12. The Switch statement in C # has a stronger function than the CASE statement in Delphi, that is, allows string expressions, which makes people break the head in Delphi, can be easily resolved in C #:? Using system ;? Public class test? {? public static void main ()? {? string s ;?? s = console.readline () ;?? switch (s)? {??? case "ok":????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? • system.console.writeline (s);???? Brenk ;????? System.console.writeline (s) ;??? Break ;??? Default:? ??? System.console.writeline ("Your Input IS {0}", s) ;???? Break;?}?}?} 13. C # provides a Foreach statement, which is convenient for the traversal of the collection element. :? Using system;? Public class test? {? Public static void main ()? {?? Int [] arr = new int [5] ;?? For (int i = 0; i <5; i )? ? // array initialization?? Arr [i] = i ;?? Foreach (int J in arr)?? // Traverse
• console.writeline (j) ;?}?}? 14. #Define #undefine instruction must be written before "real code" is used for pre-processing, with prerequisites, we can compile. The following is an example of a pre-processed definition:? # Define a? #If a? #Define b? #ENDIF? Below is an example of condition compilation, use four conditional compile statements for C # support:? Using system;? Public class Test? {? Public static void main ()? {?? #If debug?? Console.writeline ("debug message");? #Elif Normal?? Console.writeline ("Normal Message");? #Else ? #ndif?}?}? In addition, we can make a warning and error prompt by combining conditional compilation and # warning. 15. The try ... catch ... Finally ... statement processing exception is provided in C #, and the Throw statement is used to throw an exception. Let's give a simple example: • use system; public class test? {? Public static void main ()? {?? Try? {??????????????????????????????????????????????????????????????????????????????????????? ? Catch (Exception E)? {?? console.writeline ("catch the exception: {0}", E.MESSAGE);?}?? finally? {?? console.writeline ("Perfect end ");?}?}?}? Catch the Exception: My Exception? Perfect end.16. C # declared class's format as follows:? Attributes class-modifiers Class Identifier Class-Base Class-Body? Class -Modifiers can be one or several combinations: New public protected, in which public protected and private are similar to Delphi, the other meanings are as follows:? New: Allows only in nested category declarations, It is shown that the class hides the success of the same name with the base class by inheriting from the base class. • The use of the NEW keyword is similar to Reintroduce in Delphi. INTERNAL: Only its package can access? Abstract: Abstract class, can not create instances of this class? Sealed: Seal, not allowed to be inherited, similar to Final17 in Java, similar to Delphi Self keyword. Base is similar to the Super Keyword in Java. 18. C # and Java, all methods of using the same name as the class name as constructor; and the destructor is in front of the name. 19. C # also supports the overload of the method, which is more simple than Delphi, no keywords are required in C #.
20. Support operator overload in C #, allowing overloaded operators as: -! ~ - true false * /% & | ^ << >> ==! => <> = <=, Overload The operator must be defined in the class, and it is implemented by a class static method. An example of a heavy-load operator is given below: • Using system; PUBLIC CLASS Player? {? Private int Jing;? Private int in;? Pipe int jingli;? Private int neili;? Public player ()? { ????? qi = 50;? jingli = 50;? neili = 50;?} ?? public static player operator (Player P)? {?? p.jing = 100;? ? p.QI = 100 ;?? p.jingli = 100 ;?? p.neili = 100 ;?? RETURN P;?}? public void hp ()? {?? string msg ;?? msg = "jing: {0} / tjingli: {1} / nqi: {2} / t / tneili: {3}";? console.writeline (msg, jing, jingli, qi, neili) ;?} ??} PUBLIC CLASS TEST? {? public static void main ()? {?? player p = new player () ;?? p.hp () ;?? p ;?? console.writeline ("Player P Updated!") ;? p.hp () ;?}?} • The overload of the binary operator is similar to one yuan, and will not be described here. 21. In front of the Field of the class, add the readonly keyword, that is, the field is read-only.
Similar to the Read Write keyword in Delphi, the GET SET keyword is provided, the following is a simple example:? Using system; public class file? {? Private string filename? {? Public string filename? {?? Get ?? {?? Return ffilename;?}?? set?? {??? IF (ffilename! = value)???????}?}?}? public class test? {? Public static void main ()? {? file f = new file ();? f.FileName = "filename" ;? console.writeLine (f.filename) ;?}?}? C # index value is also Implement using the GET SET keyword:? Using system;? Public class myclass? {? Private int [] INTARR = new int rt [8] ;? public int this [int index]? {?? Get?? {???? Return INTARR [INDEX];?}?? set?? {?? ing (INTARR [INDEX]! = value)?????????}?}?}? public class test ? {? public static void main ()? {? myclass m = new myclass ();? for (int i = 0; i <8; i )? {?? m [i] = i ;? • console.writeline (M [I]);?}?}?} 22. Add event handler to an event, implementation in C # uses = new eventhandler: for example: okbutton.click = new EventHandler (OKButtonClick); adds OkbuttonClick event to Okbuton's Click event, if you want to undo the event handler, use-= to implement.