Deep parsing of events in C # programming

Source: Internet
Author: User
Tags constructor contains count instance method modifier numeric value variable valid
Programming

An event is a member that enables an object or class to provide a bulletin. Users can add executable code to an event by providing an event handle. Events are declared using an event declaration:

An event declaration can be either an event domain declaration or an event property declaration. In each case, the declaration can consist of a collection of properties, a new modifier, a valid combination of four access modifiers, and a static modifier.

The type of an event declaration must be a representative type, and that representative type must be at least as accessible as the event itself.

An event field declaration corresponds to a domain declaration that declares one or more representative type fields. ReadOnly modifiers are not allowed in an event domain declaration.

An event property declaration corresponds to declaring a property declaration that represents a Type property. In addition to the event property declarations that contain both get and set accessors, member names and accessor declarations are the same for those property declarations and do not allow the virtual, override, and abstract modifiers to be included.

In the program text of a class or struct that contains an event member declaration, an event member is associated with a private field or property that represents a type, and that member can be used in any context that allows the use of a domain or property.

If the program text of a class or struct contains an event member declaration, this event member can only be used as the right operand of the + = and-= operator (§). These operators are used to attach or remove event handlers for event members, and the access operator of this event member controls the context in which the operation is executed.

Because + + and-= are the only operations that can be used on events outside the type that declares the event member, the external code can add or remove handles for an event, but you cannot obtain or modify the values of the underlying event field or event properties in any other way.

In the example

public delegate void EventHandler (object sender, Event e);
public class Button:control
{
public event EventHandler Click;
protected void OnClick (Event e) {
if (click!= null) Click (this, e);
}
public void Reset () {
Click = null;
}
}

There is no limit to the Click event field in the Button class. As an example of a demo, this field can be examined, modified, and used in representative invocation expressions. The OnClick method in the class button "causes" the Click event. The concept that causes an event is exactly the same as the invocation represented by the event member-therefore, there is no special language construct for causing the event. Note that the representative's call is made by checking that the guarantee represents a Non-empty post.

Outside the declaration of the Class button, member Click can only be used on the right-hand side of the + = and-= operators, as follows

B.click + = new EventHandler (...);

It attaches a delegate to the invocation list of the event click, and

B.click-= new EventHandler (...);

It removes a representation from the invocation list of the Click event.

In an operation with x + y or x = y, when X is an event member and refers to a type outside of the declaration containing the x, the result of the operation is void (opposite the value of X after Assignment). This rule prohibits external code from checking the basic representation of an event member directly.
The following example describes how an event handle is attached to an instance of the above class button:

public class Logindialog:form
{
Button OKButton;
Button CancelButton;
Public Logindialog () {
OKButton = new Button (...);
Okbutton.click + = new EventHandler (Okbuttonclick);
CancelButton = new Button (...);
Cancelbutton.click + = new EventHandler (Cancelbuttonclick);
}
void Okbuttonclick (object sender, Event e) {
Handle Okbutton.click Event
}
void Cancelbuttonclick (object sender, Event e) {
Handle Cancelbutton.click Event
}
}

Here, the constructor Logindialog creates two button instances and attaches the event handle to the event click.

Event members are typical fields, as shown in the button example above. It is not acceptable for each event to consume a domain store, a class can declare event properties to override the event domain, and use a private mechanism to store the basic representatives. (imagine that in some cases, most of the events are unhandled, and that each event is not accepted with one domain.) The ability to use attributes rather than domains allows developers to achieve a compromise between space and time. )

In the example

class control:component
{
//Unique keys for events
static ReadOnly object Mousedowne Ventkey = new Object ();
Static readonly Object Mouseupeventkey = new Object ();
//Return event handler associated with key
protected Delegate Geteventhandler (object key) {...}
//Set event handler associated with key
protected void setEventHandler (object key, Delegate handler) {...}
//MouseDown event Property
Public event MouseEventHandler MouseDown {
Get {
Return (MouseEventHandler ) Geteventhandler (Mousedowneventkey);  
}
Set {
setEventHandler (Mousedowneventkey, value);

}
//MouseUp event Property
Public event MouseEventHandler MouseUp {
Get {
Return (Mouseeventhand ler) Geteventhandler (Mouseupeventkey);  
}
Set {
setEventHandler (Mouseupeventkey, value);
}
}

Class control provides an internal storage mechanism for events. Method setEventHandler a key to represent the numeric value, and the method Geteventhandler returns the current representative associated with the key. Presumably the basic storage mechanism is designed to have no consumption associated with the null representation type and key, so no handle event consumes storage space.

Instance variable initialization function

When a constructor does not construct an initialization function or a form of base (...) Constructor initialization function that specifies the initialization specified by the variable initialization function of the instance domain declared in the class for the implicit execution of the constructor function. This is related to the assignment sequence, which is directly executed at the gate of the constructor before the implicit invocation of the direct base-class constructor. Variable initialization functions are executed in the order in which they appear in the class declaration.

Constructor execution

An instance variable initialization function and a constructor initialization function can be thought of as being inserted automatically before the first statement in the body of the constructor. Example

Using System.Collections;
Class A
{
int x = 1, y =-1, Count;
Public A () {
Count = 0;
}
public A (int n) {
Count = N;
}
}
Class B:a
{
Double sqrt2 = math.sqrt (2.0);
ArrayList items = new ArrayList (100);
int Max;
Public B (): This (100) {
Items. ADD ("Default");
}
public B (int n): base (n-1) {
max = n;
}
}

Contains a number of variable initialization functions, and also contains constructor initialization functions for each form (base and this). This example is related to the example presented below, where each annotation indicates an automatically inserted statement (the syntax used to automatically insert a constructor call is not valid, at least to demonstrate the mechanism).

Using System.Collections;
Class A
{
int x, y, Count;
Public A () {
x = 1; Variable initializer
y =-1; Variable initializer
Object (); Invoke Object () constructor
Count = 0;
}
public A (int n) {
x = 1; Variable initializer
y =-1; Variable initializer
Object (); Invoke Object () constructor
Count = N;
}
}
Class B:a
{
Double Sqrt2;
ArrayList items;
int Max;
Public B (): This (100) {
B (100); Invoke B (int) constructor
Items. ADD ("Default");
}
public B (int n): base (n-1) {
Sqrt2 = math.sqrt (2.0); Variable initializer
Items = new ArrayList (100); Variable initializer
A (n-1); Invoke A (int) constructor
max = n;
}
}

Note the variable initialization function is converted to an assignment statement, and that assignment statement is executed before the base class constructor is called. This order ensures that all instance fields are initialized by their variable initialization functions before any statements that access the instance are executed. For example:

Class A
{
Public A () {
Printfields ();
}
public virtual void Printfields () {}
}
Class B:a
{
int x = 1;
int y;
Public B () {
y =-1;
}
public override void Printfields () {
Console.WriteLine ("x = {0}, y = {1}", X, y);
}
}

When new B () is used to create an instance of B, the following output is generated:

x = 1, y = 0

Because the variable initialization function executes before the base class constructor is invoked, the value of X is 1. The value of Y, however, is 0 (the default value for int) because the assignment to Y is not performed until the base class constructor returns.

Default constructor

If a class does not contain any constructor declarations, a default constructor is automatically provided. The default constructor is usually the following form

Public C (): Base () {}

Here c is the name of the class. The default constructor completely invokes the parameterless constructor of the direct base class. If there is no accessible parameterless constructor in the direct base class, an error occurs. In the example

Class message
{
object sender;
string text;
}

Because the class does not contain a constructor declaration, a default constructor is provided. So this example is exactly equivalent to

Class message
{
object sender;
string text;
Public message (): Base () {}
}
Private constructors

When a class declares only private constructors, other classes cannot derive from this class or create instances of the class. Private constructors are usually used in classes that contain only static members. For example:

public class Trig
{
Private Trig () {}//Prevent instantiation
Public Const Double PI = 3.14159265358979323846;
public static double Sin (double x) {...}
public static double Cos (double x) {...}
public static double Tan (double x) {...}
}

The Trig class provides a set of related methods and constants, but is not shown in the example. Therefore, it declares a separate private constructor. Note At least one private constructor must be declared to avoid automatically generating the default constructor (it usually has public access).

Optional constructor parameters

The form of this (...) constructor is typically used with an association that implements optional constructor parameters. In this case,

Class Text
{
Public Text (): This (0, 0, null) {}
public Text (int x, int y): this (x, y, null) {}
public Text (int x, int y, string s) {
Actual Constructor Implementation
}
}

The first two constructors provide only the default values for missing parameters. All two use a This (...) constructor to invoke the third constructor, which actually does the work of initializing the new instance. The effect is those optional constructor parameters:

Text T1 = new text (); Same as Text (0, 0, NULL)
Text t2 = new text (5, 10); Same as Text (5, NULL)
text T3 = new text (5, "Hello");

destructor

A destructor is a member that implements the behavior that destroys an instance of a class. Destructors use a destructor declaration to declare:

An identifier declared by a destructor must be named for the class that declares the destructor, and if any other name is specified, an error occurs.


The body of a destructor declaration specifies a statement to be executed in order to initialize a new instance of a class. This is related to the body of an instance method with a void return type.

Example

Class Test
{
static void Main () {
A.F ();
B.f ();
}
}
Class A
{
Static A () {
Console.WriteLine ("Init A");
}
public static void F () {
Console.WriteLine ("A.F");
}
}
Class B
{
Static B () {
Console.WriteLine ("Init B");
}
public static void F () {
Console.WriteLine ("B.f");
}
}

Produces or is the following output:

Init A
A.f
Init B
B.f

Or the following output:

Init B
Init A
A.f
B.f



Related Article

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.