The language of C # is detailed

Source: Internet
Author: User
Tags stack trace

The previous article was written in C # 's core language, which is a generalities. This article continues the study of C #, and begins to detail the C # language, which mainly includes delegates, events, and exception handling.  I. Delegation  to understand the concept of a delegate, you must know what a function pointer is.   A function pointer is an indirect reference to a function that supports the invocation of a function through a variable. With a function pointer, we can pass the function as a parameter or as a return value. function pointers can make your application more flexible, scalable, and scalable. However, function pointers are not type-safe.  from the perspective of life, I think the function pointer is like a courier point. Here, when we need it, we can use it to pick up a piece of mail.  A "delegate" is an abstraction of one or more function pointers. A delegate is a reference type that has a signature and return type. Events are one of the most useful delegate applications. The event will be described in detail later. The  Following is an overview of the general process of delegation: generally includingdefine, create, and Invokethese three steps.  (1) The delegate keyword is used to define a new delegate. The following code defines a new delegate, a class named Delegateclass: A delegate can be defined in a namespace, in a class, but not in a method as a class field or as a local variable. 
public delegate int Delegateclass (string info); Define a delegate

(2) The new keyword is used to create an instance of a delegate. A delegate's constructor cannot be overloaded. There are three different scenarios in which the following code is the three cases in which classes are initialized:

A) For an instance method, use the Object.Method format

B) for a static method, take the Class.method format

c) For methods and delegates that are contained in the same class, neither the object name nor the class name is required.

public delegate void Delegateclass ();p Ublic class constructors        {public            static void Main ()            {                Delegateclass Del1 = new Delegateclass (constructors. MethodA);                Instantiation under static methods                delegateclass Del2 = new Delegateclass (MethodA);                The specified method and delegate are contained in the same class under the instantiation                zclass obj = new Zclass ();                Delegateclass del3 = new Delegateclass (obj. MethodB);                Instantiation under instance method} public            static void MethodA ()            {            }} public        class Zclass        {            Public  void  MethodB ()            {            }        }

    (3) Invoke method invokes the delegate. If the delegate contains a function pointer, the return of the function becomes the return of the delegate. When multiple function pointers are stored to the specified delegate, the return of the last function becomes the delegate's return.    two. Events     in the learning of VB, I learned that the word is: with the event driver. When programming, we also want to implement a function, just write the code in the corresponding event. For example: Click on the "Login" button to enter the computer room charge system main interface. We can write the code under the Click event under the command button to drive the program.   in this book C #, an event refers to an object or class that wants to notify someone that something has happened (another class, not another object) that the other person is referring to. This is a change after the addition of object-oriented thinking, all of which are dealt with in the class.   any object or class that is interested in an event can subscribe to the event. The subscriber registers for an event by submitting a delegate. The delegate must be single-role and contain only a single function pointer, which is the subscriber's response to the event. When the specified event is raised, the Publisher invokes the function and gives the subscriber an opportunity to respond to the event. The function is called an event handler. Events can have multiple subscribers, and events without subscribers are not raised.   said a lot of professional language, I think a simple understanding, in fact, is an event can be accessed multiple times, so that the corresponding processing procedures; it can be no access, But such events are not to be triggered.   (1) The event keyword is used to define an incident   
<pre name= "code" class= "CSharp" >accessibility event Delegatename EventName
(2) Public or protected keywords are generally an accessibility setting for an event
public delegate void Delegateclass ();
<pre name= "code" class= "CSharp" >public event Delegateclass MyEvent;
(3) The Add and remove methods are used to subscribe  to and unsubscribe from (4) The event is raised with the call operator "()", which is raised by adding the call operator to the event.
public void SomeMethod () {      if (anevent!=null)      {          anevent (null,null);}      }
Three. Exception handling

What is an exception? An exception is an application exception event or an error condition that is classified as a system exception and an application exception.

System exceptions are thrown by the common language runtime (CLR), including null references, memory leaks, divide by 0, and stack overflow exceptions. Application exceptions, which are seen as custom exceptions, are thrown by the application.

(1) Exception examples

One of the common exceptions is to divide by 0, which is 0 as the divisor. As in the following code, the program was terminated by 0 except for the exception.

public static void Main () {       int var1=5,var2=0;       Var1/=var2;//exception occurs}
put the code that could produce the exception in a try block, because the code in the try block is protected by an exception, so that the exception can be caught. The catch block handles the exception and displays a stack trace.

public static void Main ()        {            try            {                int var1 = 5, var2 = 0;                Var1/= var2;//exception occurs            }            catch (DivideByZeroException except)            {                Console.WriteLine (" Exception "+ except. StackTrace);            }        }

The result of this operation is to alert the program to exactly which line is wrong:


(2) Structured exception handling

This is the name of a tool that specializes in exception handling. It determines when code is protected and where to catch and handle an exception by evaluating the stack.

A) Try statement: monitor, monitor for exceptions in protected code.

The following is a boundary overflow handling error that occurs when an array boundary is exceeded.

public static void Main ()        {            try            {                MethodA ();            }            catch (Exception except)            {                Console.WriteLine (except. Message);            }        }        public static void MethodA ()        {            int[] values = {1, 2, 3, 4};            for (int count = 0; count <= values. Length; ++count)            {                Console.WriteLine (Values[count]);            }        }

The result is an exception in the unprotected MethodA method, and the range of main calls to Methoda,main includes MethodA, so the try block extension in main is protected to MethodA. The exception is captured in main.

b) Catch statement: Filter and handle exceptions. Where filters can help us catch all kinds of exceptions.

The catch filter is optional, and the default is catch all. In (1), the dividebyzeroexception of an exception example is specifically caught by 0 except for the exception. The following code belongs to a default:

public static void Main ()        {            try            {                int var1 = 5, var2 = 0;                Var1/= var2;            }            Catch            {                //catch remaining managed and unmanaged exceptions            }        }

c) Finally statement: End processor. Plays a purpose of shutting down files, releasing a database, or other administrative resources.

The following is a typical end processor:

Using system;using system.io;namespace consoleapplication1{public    class FileWrite    {public        static void Main ()        {            StreamWriter sw = null;            Try            {                SW = new StreamWriter ("Date.txt");                Sw. Write (DateTime.Now.ToLongTimeString ());                throw new ApplicationException ("exception");                Dangling code            }            finally            {                sw. Close ();                Console.WriteLine ("File Closed");}}}    
d) Statement usage specification

Use must be paired with a catch or finally statement. There can be 0 to many catch statements and a try statement in combination, with no or only finally one statement. If the catch and finally statements appear at the same time, the catch statement should precede the finally statement.

Four. Summary

This part of the study of the Commission has been re-recognized again, before always found it difficult to understand, now feel in fact from the life to see, entrusted everywhere. How to define, how to call, in different situations how to properly instantiate, this is the harvest in this time learning. For the try-catch-finally statement, is also very early written, it seems relatively simple, is actually rich in content, now we are all in the debugging phase can be dealt with, but later on is not the same, the abnormal situation may often encounter, so this is also a very basic learning.

In the final review stage, learn some C # things, the day after tomorrow will be school, machine room reconstruction, will really start. Come on!



The language of C # is detailed

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.