[C # details] (1) Automatic attributes, initiators, and extension methods,

Source: Internet
Author: User

[C # details] (1) Automatic attributes, initiators, and extension methods,

Download Code: Click here to download

Directory
  • Preface
  • Attributes and automatic attributes
    • Attribute
    • Automatic attributes
  • Initializer
    • Object initializer
    • Set Initiator
  • Extension Method
    • No parameter Extension Method
    • Extension Method with Parameters
  • End
Preface

Wish everyone a happy New Year!

A new year, a new start. It has been almost two months since I came to the blog Park to settle my house. Reading blogs, writing blogs, commenting, and answering questions every day has gradually become a habit. I can obviously feel that I can learn a lot in my blog. I have benefited a lot from every aspect, whether it's a technical article or a series of narrative experiences or essays that express my feelings. I don't know if everyone is the same as me. I feel that there is a special magic in the blog Park. if you're okay, you just want to take a look and see if someone has published a new article, when you are tired, you can relax yourself by looking at non-technical things.

Sometimes I may ask myself: Is it worthwhile to spend the time and energy on the blog Park? After all, this is also a "voluntary labor". It does not create any value for itself. In other words, it does not make money. But every time I think about this question, I will be more determined by my choice. There are three reasons to stick to the blog Park:

  • The continuous use of technical knowledge in the blog Park to improve their technical level is undoubtedly increasing their own value. I think the most essential problem for higher wages is to increase its own value. For our technical staff, the wider the knowledge, the deeper the technology, the faster the coding speed, the higher the quality, and the stronger the problem solving, the higher our value. The blog Park is helpful to us in these aspects.
  • Non-technical blogs and news in the blog Park allow us to learn about the work, life, and emotional status of people in the same industry. It can also provide industry news for programmers. This gives me a clearer understanding of myself and people in the same industry, including the entire industry. It gives me a clearer understanding of my position in the industry, so that I can grasp myself more accurately and better plan my career.
  • The blog garden is a stage for demonstration. I have seen many blogs with recruitment advertisements for my own company, or marketing my own products and websites. Yes, they use this platform where high-quality programmers gather to advertise for themselves, and they are still free of charge. Why not. For me, there is no need to advertise for the moment, but through the blog, more people will know me and learn about my technical skills, there must be no harm. I am making a profit when I advertise for myself for free.

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

Go back to our blog. I have previously written 10 MVC5 + EF6 + Bootstrap3 series tutorials, and will continue writing this article this year. After all, I am very optimistic about these three technologies. When writing this series, I regret that many technical points of C # have little to do with MVC. If you write in detail, you are afraid to run your questions. If you do not write it, you are afraid that the readers will not understand it. It has always been a bit embarrassing. Therefore, I opened this topic [C # details] to explain the things that I had to talk about but didn't talk about. This gives you peace of mind. Therefore, reading the [C # details] series will make you more clear when you look at the MVC5 + EF6 + Bootstrap3 series. When looking at [C # details], you can also go to MVC5 + EF6 + Bootstrap3 to find the actual application scenarios of these knowledge points. In this way, the effect should be good.

Attributes and automatic attributes

Before interpreting automatic attributes, it is necessary to talk about attributes.

Attribute

We know that to comply with the object-oriented programming principles, the variables in a class should be private. As follows:

class Student{    private int _id;}

This ensures the encapsulation of classes. But there is always a way to access it from the outside, otherwise there is no need to exist. Therefore, attributes are used here. The Code is as follows:

 1 class Student 2 { 3     private int _id; 4     public int Id 5     { 6         get 7         { 8             return _id; 9         }10         set11         {12             _id = value;13         }14     }15 }

In the above Code, row 4th defines an attribute named Id, which can be used to access the private Variable _ id. The "get" and "set" accessors are included in the Id attribute. The "get" accessors are used to obtain the values of private variables. The "set" accessors are used to assign values to private variables. The following code shows how to use attributes:

1 Student student = new Student();2 student.Id = 3;3 Console.Write(student.Id);

Row 3 calls the set accessor to assign a value to the Id, and row 3 calls the get accessor to obtain the Id value. The result is as follows:

In addition, we can add code to the get accessors to process the output or add code to the set to process the assignment. Example:

 1 class Student 2 { 3     private int _id; 4     public int Id 5     { 6         get 7         { 8             return _id + 100; 9         }10         set11         {12             if (value > 0)13             {14                 _id = value;15             } 16             else17             {18                 _id = 0;19             }20         }21     }22 }

The code in the second line adds 8th to the Id attribute in the output, row 12-19, so that if the value of the Id attribute is less than 0, the value is 0.

Use the following code to call the above class.

1 Student student = new Student();2 student.Id = -3;3 Console.Write(student.Id);

After the second row is executed, the Id attribute will be assigned 0 values, and the value will change to 100 in the output.

Automatic attributes

Attribute definition is cumbersome. here we can use automatic attributes to simplify code. We also define an attribute that does not perform any special processing on input and output. we can write it like this:

1 class Student2 {3     public int Id { get; set; }4 }

The first row is our automatic attribute. The syntax is to add {get; set;} after the attribute ;}. Saves the definition of private variables and accessors, and only one row can be done, but its functions are the same as those of previous properties. This is the benefit of automatic attributes. However, automatic attributes cannot implement special processing on input and output as mentioned above.

In addition, if you want to change an attribute to read-only, you can use the automatic attribute to write it like this:

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

In the code above, the first line of the Code adds private to the front of the set accessors, and the attribute assignment cannot be called externally. Naturally, it becomes a read-only attribute. However, in Row 3-6, remember to add the constructor to assign the initial value to the attribute. The call method of this class is as follows:

1 Student student = new Student(3);2 Console.Write(student.Id);

Row 3 assigns a value to the Id using the constructor, and row 3 obtains the assigned value. The result is as follows:

Click to view automatic attributes

Initializer

The initiators are divided into object initiators and set initiators. The following is a one-to-one introduction.

Object initializer

The role of the Object initializer is to simplify the code for initializing a class. For example, the following class:

class Person{    public string Name { get; set; }    public int Age { get; set; }    public string Address { get; set; }}

We usually need to initialize it and assign values to it like this:

Person person = new Person();person.Name = "Slark";person.Age = 100;person.Address = "Xi'an";

Here we use a statement to create an object and add three rows of value assignment statements. Here, the variable "person" appears four times, which is tedious. Replace these operations with the object initiator:

Person person = new Person { Name = "Slark", Age = 100, Address = "Xi'an" };

In the same effect, the object initiator only uses one line, which is concise! You can see that the object initiator combines the created object and the value assignment into one row, and the value assignment is done in the braces that follow. Here, you can assign values to all attributes, or assign values to some attributes.

Set Initiator

Since we want to talk about the set initiator, we will first create a set:

List<int> intList = new List<int>();intList.Add(1);intList.Add(2);intList.Add(3);

Well, here we use four lines of code to create a set of three elements. The appearance of the Set initiator greatly reduces the amount of code for this operation. The corresponding set initiator code is:

List<int> intList = new List<int> { 1, 2, 3 };

Well, I really did not write much. The principle of the Set initializer is also very simple, that is, it silently calls the Add method of List for us to Add these three elements in turn.

Here we will give you an example of using the set initializer and object initializer comprehensively:

List<Person> personList = new List<Person>{    new Person { Name = "Slark1", Age = 101, Address = "Xi'an1" },    new Person { Name = "Slark2", Age = 102, Address = "Xi'an2" },    new Person { Name = "Slark3", Age = 103, Address = "Xi'an3" }};

In the code, the set initializer initializes the personList and the object initializer initializes three Person object instances. This saves a lot of code.

Click here to view the initialization application instance

Extension Method

Extension Method. Simply put, you can add a method to the class without changing the existing class. I think the biggest significance of the extension method is that we can add custom methods to classes that cannot be modified at all, such as String. Since it cannot be added through modification, it can only be extended.

This reminds me of the Open-Close Principle (OCP): A software entity should be Open to the extension and closed to the modification.

Now that the class is open to extension, let's try it!

No parameter Extension Method

First try to add a DoubleString Method to the String, that is, output the String twice.

First create a static class StringExtension:

 1 static class StringExtension 2 { 3     public static string DoubleString(this string str) 4     { 5         return str + str; 6     }
7 }

Note that in Row 3, we put the method to be extended into a class, and this class must be a static class and should be added with static. Class Name. Row 3-6 is the method we want to expand. This method is special. It should be written as a static method during definition, but it should be used as an instance method during call. The parameter of this method is written as this string str to add this method to the String class. However, this method cannot be called with parameters.

The call method is as follows:

string str = "ABCD";Console.Write(str.DoubleString());

We can see that the extended method DoubleString is treated as an instance method when called, and there is no parameter. The running result is as follows:

The results meet our expectations.

Extension Method with Parameters

What if I want to add parameters to the extension method? The sample code is as follows:

 1 static class StringExtension 2 { 3     public static string RepeatString(this string str, int row,int column) 4     { 5         string s = string.Empty; 6         for (int i = 0; i < row; i++) {  7             for (int j = 0; j < column; j++) 8         { 9             s += str + " ";10         }11             s += "\r\n";12         }13             return s;14     }15 }

Note that there are three parameters in Row 3. The last two parameters will be assigned when the extension function is called, here, the RepeatString function will write a string into a matrix of several rows and columns.

The call method is as follows:

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

The first parameter corresponds to the second parameter during definition, and the second parameter corresponds to the third parameter during definition. The result is as follows.

Click here to see the Extension Method Instance

End

Call ~ I finally finished writing, and my back pain and leg cramps.

If you like it, we recommend it!

Author:Slark. NET

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

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you have any questions or suggestions, please give me some further information. Thank you very much.

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.