How do I learn C # language? diligence is king. Part 3 OOP

Source: Internet
Author: User
Tags finally block
Class class class class class class category Part 3: OOP Technology Class class class class class class class class 1 constructor and destructor Does the compiler declare the default constructor? Can you declare the default constructor? If you declare a constructor, the compiler does not declare the constructor. Ealed class pair { Public pair (int x, int y) { This. x = x; // This indicates that when we create an object (instance, // This indicates the current object we have created. Y = y; } The Parameter Y of the constructor is assigned a value using the field y. The reason the compiler passes is that field Y has been assigned an initial value. In fact, if the field y is not initialized, the compiler will still pass, If the default value of field y is 0, no explicit initialization of field Y in the constructor will occur. Two interfaces, three inheritance, four polymorphism, one is implemented through overloading, and the other is implemented through Virtual Methods + inheritance. Define a base class, which is just a general description of things, The method is defined as virtual (vitual ). Equivalent to a general framework We can derive many different functions as needed. Is declared as a virtual method overwrites (overridden) to the base class) Each derived class can use the same function name. In this way, multiple Derived classes implement polymorphism. Note: to override a virtual method, you must use the keyword override in the derived class. The third abstract class (specifically for derived or inherited Services) We can define an abstract class specifically for inheriting polymorphism and only providing the most basic description of the abstract class. For example, an abstract class animal only defines some attributes and methods that all animals have. Abstract classes must use the abstract keyword for both Class names and Methods Because abstract classes are specialized for inheritance or derivation services, do not keep their life as sealed (sealed) Sealing classes as normal classes, but cannot be derived or inherited. The data member of the sealed class cannot be declared as protected. 5. Exception Handling 1 Exception Handling can provide a good ability to interact with users. If you do not need to handle exceptions, Obscure error message and Termination Program For example Using system; Class 1 { Public static void main () { Int [] myarray = new int [5]; Try { For (int ctr = 0; CTR <10; CTR ++) { Myarray [CTR] = CTR; } } Catch { Console. wreteline ("the input is incorrect. Check it later "); } } } When an exception occurs, the program immediately jumps to the catch statement instead of reporting an error and stopping the program. The following is a clever use of exceptions: Calculate the absolute value of [(the square of X-the square of Y) under Z = root number] + x Flort x, y, z; Try { Z = math. SQRT (x * x-y * y ); } Catch { Z = math. SQRT (y * Y-x * X ); } Finally { Z = z + X; } You only need to enter the value of x y. This is a method for calculating the absolute value. The second catch statement is used together to obtain the absolute value. The above program only uses catch to catch exceptions. It can also include parameters in catch to determine which exceptions are thrown. Catch (system. excption e ){} Using this method, the system will handle some exceptions that are set by default. Excption is a pre-defined class for exception handling. Here E is an exception type variable. Here, we cannot define some information about the e-tabulation. The system searches for and outputs relevant information. Using system; Class 1 { Public static void main () { Int [] myarray = new int [5]; Try { For (int ctr = 0; CTR <10; CTR ++) { Myarray [CTR] = CTR; } } Catch (system. excption E) { Console. wreteline ("the input is incorrect. Check it quickly: \ n {0}", e ); } } } 2 Finally The finally statement is executed no matter whether the try statement is successfully executed. 3. Common exceptions Exceptions in C # are used to handle system-level and application-level error states. It is a structured, unified, and type-safe processing mechanism. The exception mechanism in C # is very similar to the exception Mechanism in C ++, but there are some important differences: In C #, all exceptions must be represented by an instance of the class type derived from system. Exception. In C ++, any value of any type can be used to indicate an exception. In C #, The Finally block (section 8.10) can be used to compile the termination of execution in the case of normal execution and exceptions. Code . In C ++, it is difficult to write such code without repeating the code. In C #, system-level exceptions, such as overflow, Division by zero, and null, all correspond to the exception classes they match, and are in the same status as application-level errors. System. arithmeticexception Exception during arithmetic operation (Such as system. dividebyzeroexception and system. overflowexception. System. arraytypemismatchexception When an array is stored, if the storage fails because the actual type of the stored element is incompatible with the actual type of the array, This exception is thrown. System. dividebyzeroexception This parameter is triggered when a zero-division integer is used. System. indexoutofrangeexception This is triggered when you try to use a subscript index array that is less than zero or exceeds the limit of the array. System. invalidcastexception When the explicit conversion from the base type or interface to the derived type fails at runtime, This exception is thrown. System. nullreferenceexception This exception is thrown if null reference is used when a reference object is required. System. outofmemoryexception Triggered when the attempt to allocate memory (via new) fails. System. overflowexception This is triggered when the arithmetic operation in the checked context overflows. System. stackoverflowexception When the execution stack is exhausted due to saving too many pending method calls, This exception is thrown; this usually indicates that there is a very deep or infinite recursion. System. typeinitializationexception This is triggered when a static constructor raises an exception and no catch clause can be captured. 4 Multiple catch statements will be executed in sequence. The dedicated exception program is put in front. If the processing fails, you can put a common Exception Handling statement The order of the two catch statements is very important. We can only put specific processing at the beginning. An exception that is usually followed by an exception cannot be changed. If an array subscript overflow error occurs System exception dedicated to handling array table Overflow // No e output here The second catch processing is comprehensive to prevent other errors. If no overflow error occurs, and other errors occur, for example, the divisor is zero. The system will not execute the first catch statement, but the two catch statements executed Output result The input is incorrect. Check the input: System. dividebyzeroexception: attempted to divide by zero // This is the output information defined by the system. Method 2 Throw Using system; Class 1 { Public static void main () { Int [] myarray = new int [5]; Console. writeline ("..."); ... // Related procedures If () { Throw (New dividbyzeroexception ()); } } } Do not forget the New Keyword. Remember the above format. In addition, throw statements are generally used in combination with if statements. 5. Custom exceptions Base Class C # all classes of object are derived from object. It is. the root class of the. NET Framework class hierarchy is objectobject. The GetType tostring method returns an object (Instance) de data type, and the GetType tostring method returns a name (string) indicating the current object) any object can use these two methods. We can even declare a constant PI as a class using system; sealed class PI {public static float NBR; static public float Val () { Return (NBR ); } Static Pi () { NBR = 3.1415926f; } Class 1 { Public static void main () { Object x = New Pi (); Console. writeline ("tostring: {0}", X. tostring ()); Console. writeline ("type: {0}", X. GetType ()); Console. writeline ("tostring: {0}", 123. tostring ()); Console. writeline ("type: {0}", 123. GetType ()); Output result: Tostring: pi Type: pi Tostring: 123 Type: system. int32 Because object is the base class of all classes, you can define an object type variable. And point it to the PI class The X type is pi. After tostring is used for X, Pi is obtained. The following two sentences are analyzed: Because all things in C # Are objects and are derived from objects 123 these numbers are no exception } Boxing unboxing in section 6, we say that everything is derived from an object, and everything in C # is an object, which is not very accurate, it can be regarded as the first 123 of the object. Actually, literal values are implicitly converted into objects. The packing concept is: converting the value type to the reference type (object) unpacking concept: convert the displayed reference type to the Value Type Packing. When we use it, the system will automatically unpack the box. The displayed value must be the "Eight is as" keyword in the corresponding data type variable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.