[Detailed in C #] (1) Automatic attributes, initializers, extension methods

Source: Internet
Author: User

Code Download: Click I download

Directory
    • Objective
    • Properties and Automatic properties
      • Property
      • Automatic properties
    • Initialization device
      • Object initializer
      • Collection initializer
    • Extension methods
      • No parameter extension method
      • Extended method with Parameters
    • End
Objective

First of all, I wish you 2015 Happy New Year!

A new year, a new beginning. It's been almost two months since I came to the blog park. Reading blogs, blogging, commenting and answering questions on a daily basis has gradually formed a habit. Can obviously feel the bubble in the blog Park really can learn a lot, whether it is a technical article or some narrative experience, express feelings of the essay, I have benefited from all aspects. Do not know if everyone is the same as me, is that the blog Park has a special magic, so you do not want to go up and look at the above is not another person sent a new article, and tired when the above to see the non-technical things can also relax themselves.

Sometimes I ask myself: Is it worth the time and energy spent on the blog park? After all, this is also considered "voluntary labor", do not create any value for themselves, popular point is not to make money. But every time I think about it, I will be more determined by my choice. There are three reasons to adhere to the blog park:

    • Constantly using the technical knowledge of the blog park to improve their skills, this is undoubtedly increasing their own value. I think the most essential problem to get a high salary is to raise one's own value. For our technical staff, is the broader knowledge, mastery of the deeper technology, the faster the speed of the code, the higher the quality, solve the problem of the more powerful, our value is higher. The blog park is helpful to all of us in these respects.
    • Blog Park in the non-technical blog and news, so that we can learn about the same industry people's work, life and emotional state. and to provide relevant industry news for programmers. This allows me to have a clearer understanding of myself and the people in the industry, including the industry as a whole. It gives me a clearer understanding of where I am in the industry, so that I can more accurately grasp myself and better plan my career.
    • The blog Park is a showcase of the stage. I see a lot of blog posts in their own company's recruitment ads, or marketing their products, their own website. Yes, they use this high-quality programmer to assemble the platform and advertise for themselves, and it's free. That's why. For the present, I do not need advertising for the moment, but through the blog to let more people know me, I know that the level of technology, there must be hundreds of profits and no harm. Free to advertise for themselves, how to see is earned.

Therefore, sticking to the blog Park is definitely a realistic decision. I believe I can keep doing it.

Back to our blog itself. Previously wrote 10 MVC5 + EF6 + BOOTSTRAP3 Series tutorials, this year will continue to write down. After all, these three technologies are my big favor. While writing this series, it's a pity that many of C # 's own technical points have little to do with MVC. The details of the words are afraid of the topic, do not write afraid of readers do not understand, has been a bit awkward. So I opened this topic [C # in detail] to explain what I had to say and what I didn't say one by one. So I feel relieved. So looking at the [C # Detail] series makes it clearer when you look at the MVC5 + EF6 + BOOTSTRAP3 series. and see [C # Detailed] can also go to MVC5 + EF6 + BOOTSTRAP3 to find these knowledge points of the actual application scenario. This complements each other, and the effect should be good.

Properties and Automatic properties

It is necessary to speak about attributes before interpreting automatic attributes.

Property

We know that to conform to the principle of object-oriented programming, variables inside a class are best private. As shown below:

class student{    privateint  _id;}

This guarantees the encapsulation of the class. But to encapsulate it must have a way to access it from the outside, otherwise there is no need to exist. So we're going to use attributes here. The code looks like this:

1 classStudent2 {3     Private int_id;4      Public intId5     {6         Get7         {8             return_id;9         }Ten         Set One         { A_id =value; -         } -     } the}

The 4th line in the code above defines a property named ID, which allows access to the private variable _id. The id attribute has a GET and set two accessors, which are used to get the value of a private variable, and the set accessor is used to assign a value to a private variable. The following code shows how to use the property:

1 New Student (); 2 3 ; 3 console.write (student. ID);

Line 2nd calls the set accessor to assign a value to the ID, line 3rd, call get accessor to get the ID value displayed, the result is as follows:

property, we can add code to the get accessor to process the output or add code to the set to handle the assignment. Examples are as follows:

1 classStudent2 {3     Private int_id;4      Public intId5     {6         Get7         {8             return_id + -;9         }Ten         Set One         { A             if(Value >0) -             { -_id =value; the             }  -             Else -             { -_id =0; +             } -         } +     } A}

The 8th line of code makes the ID property add 100 to the output, 第12-19 the row so that the id attribute is assigned a value of less than 0 if the value is assigned to 0.

Call the above class with the following code.

1 New Student (); 2 student. Id =-3; 3 console.write (student. ID);

The second line executes after the ID property is assigned a value of 0 and then becomes 100 on output.

Automatic properties

The definition of a property is tedious, and here we can use automatic attributes to simplify the code. The same is the definition of a property that does not do any special processing on the input and output, which we can write:

1 class Student 2 {3      Public int Get Set ; } 4 }

The 3rd line is our automatic attribute, which is written by adding {get; set;} after the property. The definition of a private variable and accessor is saved, but the function is exactly the same as the previous attribute. This is the benefit of automatic attributes. However, automatic attributes do not implement special handling of input and output as mentioned earlier.

In addition, to make a property read-only, use the automatic attribute to write:

 1  class   Student  2  3  public  Student (int   ID)  4   { 5  ID = ID;  6   7  public  int  Id {get ; private  set  ;}  8 } 

In the above code, the 7th line in front of the set accessor with private, the property assignment can not be called externally, and naturally become a read-only property. But on the 第3-6 line, remember to add a constructor to assign an initial value to the attribute. The calling method for this class is as follows:

1 New Student (3); 2 console.write (student. ID);

Line 1th assigns a value to the ID using the constructor, and the 2nd row gets the assigned value. The results are as follows:

Dot I see Auto properties

Initialization device

The initializer is divided into an object initializer and a collection initializer. described below.

Object initializer

The function of the object initializer, simply put, is to make the code we initialize a Class A little bit more concise. For example, the following class:

class person{    publicstringgetset;}      Public int Get Set ; }      Public string Get Set ; }}

We're going to initialize it and assign a value to it, which is usually the case:

New"slark " "Xi ' an  ";

Here we use a line to create an object statement, plus three rows of assignment statements. Here the light person this variable appears 4 times, tedious. Use the object initializer in place of these actions:

New " Slark "  - " Xi ' an " };

The same effect, the object initializer only used a line, concise! You can see that the object initializer will create the object and assign it to a line, where the assignment is done in the curly braces behind it. Assignments here can assign values to all properties, or assign values to some properties.

Collection initializer

Now that we're going to talk about the set initializer, we'll start by creating a collection:

list<intnew list<int>(); Intlist.add (1); Intlist.add (  2); Intlist.add (3);

OK, here we create a collection of 3 elements with 4 lines of code. The advent of the collection initializer greatly reduces the amount of code we have for this kind of operation. Its corresponding set initializer code is:

list<intnew list<int123 };

Well, it's really a lot less written. The principle of the set initializer is also very simple, that is, it silently calls the list of the Add method for us to add the 3 elements.

Here we give a comprehensive example of the use of a set initializer and an object initializer:

List<person> personlist =NewList<person>{    Newperson {Name ="Slark1", age =101, Address ="Xi ' An1" },    Newperson {Name ="SLARK2", age =102, Address ="Xi ' an2" },    Newperson {Name ="Slark3", age =103, Address ="Xi ' AN3" }};

The code initializes the personlist with the collection initializer, and initializes the 3 person object instances with the object initializer. That's how much code is saved.

Point I see the initializer application instance

Extension methods

The extension method, simply put, is the ability to add methods to this class without changing the existing class. I think the biggest implication of the extension approach is that we can add our own custom methods to classes that we simply cannot modify, such as String. Since it cannot be added by modification, it can only be extended by extension.

It reminds me of the open and closed principle (Open-close PRINCIPLE,OCP): A software entity should be opened to the extension and turned off for modification.

Now that the class is open for expansion, let's try it out!

No parameter extension method

Try adding a Doublestring method to the string first, which is to output the strings two times.

First create a static class Stringextension:

  1  static  class   Stringextension   {  3  public  static  string  doublestring (string   str)   4    5  re Turn  str + str;   } 
7}

Note In line 1th, we put the method that we want to extend in a class, and this class must be a static class, add static. The name of the class casually up, does not matter. The 第3-6 line is the way we want to extend it. This method is special and is written as a static method at the time of definition, but it is used when the instance method is called. The parameter of this method is written in this string str, which indicates that the method is to be added to the string class. However, this method does not add arguments to the call.

The calling method is as follows:

string " ABCD " ; Console.Write (str. Doublestring ());

As you can see, the extended method doublestring is invoked as an instance method and has no parameters. The results of the operation are as follows:

The results are in line with our expectations.

Extended method with Parameters

What if I have parameters for the extension method? The sample code is as follows:

1 Static classstringextension2 {3      Public Static stringRepeatstring ( This stringStrintRowintcolumn)4     {5         strings =string. Empty;6          for(inti =0; i < row; i++) { 7              for(intj =0; J < column; J + +)8         {9s + = str +" ";Ten         } Ones + ="\ r \ n"; A         } -             returns; -     } the}

Note that line 3rd here has a total of 3 parameters, where the last two parameters are assigned when the extension function is called, where the Repeatstring function writes a string into a matrix of several rows and columns.

The calling method is as follows:

string " ABCD " ; Console.Write (str. Repeatstring (3,4));

The first parameter at the time of the call corresponds to the second argument at the time of the definition, and the second parameter when called corresponds to the third argument when defined. The results are shown below.

Point I see Extension method instance

End

Shout ~ finally finished, waist acid back pain leg cramp.

If you like it, recommend it!

Slark.net

Source: http://www.cnblogs.com/slark/

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. If you have any questions or suggestions, please enlighten me, thank you very much.

[Detailed in C #] (1) Automatic attributes, initializers, extension methods

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.