[Yi C #] C #3.0 new features of the language object and set Initiator

Source: Internet
Author: User
Tags new set

Http://kenchell.blog.163.com/blog/static/260883092009716114946383/

In C #3.0, an object creation expression can contain an object or a collection initializer to initialize the members of a newly created object or the elements of a newly created set.

Object creation expression:

New Type (argument-List (optional) object or set preliminary trial (optional)

A New Type object or a set of preliminary testing devices

An object creation expression can omit the constructor parameter list and replace it with parentheses as an object or set initiator. Omit the constructor parameter list and replace it with parentheses to an object or set initializer is equivalent to specifying an empty parameter list.

When executing an expression for creating an object with an object or a set initializer, first call the instance constructor and then execute the initialization of the specified member or element of the object or set initiator. The object or set initializer cannot reference the object instance being initialized.

4.1.4.1 introduce the object Initiator

In traditional C #, we often use two methods to initialize a class (or struct). One is to use constructors with parameters, the other method is not to use the constructor, or the constructor does not actually assign values to fields. Instead, after applying for an instance of the class, manually assign values to its public attributes. The following is an example of a geometric point in a two-dimensional space:

Public Class Point

{

Private int xpos, ypos;

// Default constructor

Public point ()

{

}

Public point (int x, int y)

{

Xpos = X;

Ypos = y;

}

Public int x

{

Get {return xpos ;}

Set {xpos = value ;}

}

Public int y

{

Get {return ypos ;}

Set {ypos = value ;}

}

Public override string tostring ()

{

Return string. Format ("[{0}, {1}]", xpos, ypos );

}

}

For this class, we initialize it as follows:

// Call a custom Constructor

Point P = new point (1, 100,200 );

// Or manually specify each attribute

Point P1 = new point ();

P1.x = 100;

P1.y = 200;

Now we can use the C #3.0 code of the class initialization tool as follows:

VaR p1 = new point {x = 100, y = 200 };

Point P = new point {x = 100, y = 200 };

The first one is an implicit variable. Here, the point constructor is not explicitly called, but the value is set to the common x and y attributes. Here, the default constructor of the type is called, and the value is assigned to the specified attribute. In this regard, the last two instances are actually the Simplified Method of the first instance.

From the above example, we can see that:

L The object initializer is composed of a series of member initiators, which are enclosed in the {And} mark and separated by commas. Each member initializer starts with an accessible domain or attribute name of an object, followed by an equal sign, followed by an expression or an object or a collection initiator. If the object initialization includes more than one member initializer for the same domain or attribute, an error will occur.

L after the equal sign, the handling of the expression member initializer is consistent with that of the field and attribute assignment.

L after the equal sign, the member initializer of the object initiator is also initialized for a nested object. Unlike assigning a new value to a domain or attribute, the value assignment in the object initiator is considered to assign values to the domain or attribute members. A property with a value type cannot be initialized using this structure.

L after the equal sign, the member initializer of the Set initiator is also initialized for a nested set. Different from assigning a new set to a domain or attribute, the given elements in the initialization will be added to the Collection referenced by the domain or attribute. This field or attribute must be a collection type that meets the requirements specified in the next section.

L at the beginning of the object, the compiler assigns values to externally visible fields or attributes of the object in order, and calls the constructor in compilation or implicit mode, you can assign one or more values to a field or attribute.

Ipv4.2 call a custom constructor in the initialization syntax

In the preceding example, the default constructor is called implicitly during point type initialization. In fact, we are also allowed to explicitly specify which constructor to use, for example:

Point P = new point () {x = 100, y = 200 };

Of course, you can also use the self-defined constructor instead of calling the default constructor, as shown below:

Point P = new point (10, 20) {x = 100, y = 200 };

In the above Code, the execution result is that 10 or 20 of the constructor parameters are ignored, and the final instance is xpos = 100, ypos = 200. In the current point class definition, calling a custom constructor is not very useful, but it seems cumbersome. However, we add a new constructor that allows you to specify a color (the enumeration type of pointcolor) when calling the point struct, the combination of such custom constructor and initialization syntax is very powerful. Now, let's refactor the point struct. The Code is as follows:

Public Enum pointcolor

{

White,

Black,

Green,

Blue

}

Public Class Point

{

Private int xpos, ypos;

Private pointcolor C;

Public point ()

{

}

Public point (pointcolor color)

{

Xpos = 0;

Ypos = 0;

C = color;

}

Public point (int x, int y)

{

Xpos = X;

Ypos = y;

C = pointcolor. Green;

}

Public int x

{

Get {return xpos ;}

Set {xpos = value ;}

}

Public int y

{

Get {return ypos ;}

Set {ypos = value ;}

}

Public override string tostring ()

{

Return string. Format ("[{0}, {1}, color = {2}]", xpos, ypos, C );

}

}

Now let's test the following code:

Class Program

{

Static void main ()

{

Point P = new point (pointcolor. Black) {x = 100, y = 200 };

Point P1 = new point (10, 20) {x = 100, y = 200 };

Console. writeline (P );

Console. writeline (P1 );

}

}

The final result of running the program is:

[100,200, color = Black]

[100,200, color = Green]

Initialize internal type

Let's look at a practical example. We need to define a rectangle class, which uses the point type to represent the coordinates of the two points in the upper left corner and the lower right corner. The Code is as follows:

Public class rectangle

{

Private point topleft = new point ();

Private point bottomright = new point ();

Public point topleft

{

Get {return topleft ;}

Set {topleft = value ;}

}

Public point bottomright

{

Get {return bottomright ;}

Set {bottomright = value ;}

}

Public override string tostring ()

{

Return string. Format ("[topleft: {0}, {1}, bottomright: {2}, {3}]",

Topleft. X, topleft. Y, bottomright. X, bottomright. y );

}

}

Now we can use the object initialization syntax to create a rectangle instance and set its internal points as follows:

Rectangle myrect = new rectangle

{

Topleft = new point {x = 100, y = 100 },

Bottomright = new point {x = 200, y = 200}

};

This setting is much simpler, which also improves readability. At this time, we will be able to appreciate its advantages over traditional methods.

In the end, in order to allow readers to better compare and learn, we will provide its original call method:

Rectangle myrect = new rectangle ();

Point P1 = new point ();

P1.x = 100;

P1.y = 100;

Myrect. topleft = p1;

Point P2 = new point ();

P2.x = 200;

P2.y = 200;

Myrect. bottomright = P2;

Ipv4.4 set Initiator

Similar to the object initialization syntax, set Initialization is used. This syntax allows us to use a simple array type to initialize a generic container (such as list <t> ). The object type of the Set initializer can be applied must implement system. Collections. Generic. icollections <t> and specified T. In addition, there must be an implicit conversion from the type of each element initiator to T. If these conditions cannot be met, a compilation error occurs. The Set initiator calls icollection <t>. Add (t) for each specified element in sequence ). Under this constraint, containers (such as arraylist) in the system. Collection namespace cannot use this new syntax because they do not implement the required interfaces.

A set initiator is composed of a series of element initiators, which are surrounded by {And} marks and separated by commas. Each element initiator specifies an element, which will be added to the set object to be initialized. To avoid confusion with the member initiator, the element initiator cannot be a value assignment expression. The following is an example:

// Initialize a Normal Array

Int [] myintarray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Initialize an int-type generic list <>

List <int> mygenericlist = new list <int> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// The following statement is invalid. The arraylist does not implement the icollection <t> interface.

Arraylist mylist = new arraylist {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Now we apply the Point class used previously, for example:

Static void main ()

{

List <point> mypointlist = new list <point>

{

New Point {x = 10, y = 20 },

New Point {x = 100, y = 200 },

New Point {x = 1000, y = 2000}

};

Foreach (var p in mypointlist)

{

Console. writeline (P );

}

}

The program running result is as follows:

[10, 20, color = white]

[100,200, color = white]

[1000,2000, color = white]

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.