Try C # syntax sugar (automatic attribute/anonymous method/Lamda expression, etc.)-be careful with tooth decay!

Source: Internet
Author: User

-Syntactic sugar,It refers to syntaxes that do not add new features to computer languages, but are "sweet" for humans, intended to make the programming style easier to read. New features released in C #2.0 and 3.0, except that generics are not syntactic sugar, almost all other new features are syntactic sugar.

-Beginners often do not understand these syntactic sugar, so they cannot understand the real operation mode when reading the code. The most famous one isLamda expressionThe first time I saw it, many people would put a big question mark on it...

-The article will be accompanied by some code that may be confusing. Please try your best. Then we will introduce some syntactic sugar to polish it so that beginners can understand the original meaning of these syntactic sugar.

Let's do a list <t> class exercise. I will write a very painful example (it is difficult to avoid syntax sugar as much as possible ). First, I defined a student class.

public class Student{    private string num;    public string Num { get { return num; } }    private string name;    public string Name { get { return Name; } }    public Student(string num, string name)    {        this.num = num;        this.name = name;    }    public override string ToString()    {        return num + ":" + name;    }}

The findall () method of list <t> is practiced. Its declaration is as follows:

public T FindAll(Predicate<T>match)

The findall method uses predicate <t> as the parameter. predicate <t> is a delegate that references a predicate method-a method that returns a Boolean value. If the predicate returns true, there is a match.

So I wrote a findstudent class to define the predicates. This method is initialized by the student's student ID to be searched. findpredicate () receives a student object and compares the student ID of the student object with the student ID set in the constructor. True or false is returned.

Public class findstudent // corrected on 2010/4/20 thanks to terry_huang and Jack AFA for correcting {private string num name; Public findstudent (string num name) {This. num = num;
This. Name = Name;} public bool findpredicate (Student) {return student. Name = Name ;}}

Finally, search for a student named John in a console program.

  class Program    {        static void Main(string[] args)        {            List<Student> Students = new List<Student>();            Students.Add(new Student("001", "John"));            Students.Add(new Student("002", "Marry"));            Students.Add(new Student("003", "John"));            FindStudent finder = new FindStudent("John");            foreach (var student in Students.FindAll(new Predicate<Student>(finder.FindPredicate)))            {                Console.Write(student);            }        }    }

Does anyone see that this is no longer enough, especially for the lengthy usage of the findstudent class and findall?

Next we will give you a touch set.

  Sweet death you 1-Automatic attributes:You only need to specify the attribute name when defining a class. The C #3.0 compiler automatically implements the corresponding internal private variable and generates the set accesser and get accesser.

  Sweet to death you 2-Object Initial ValueItem:On the premise of automatic attributes, you can assign values to any accessible attributes or fields when creating an object without displaying the call constructor.

Based on these two features, let's modify the student class:

public class Student{    public string Num { get; set; }    public string Name { get;set; }    public override string ToString()    {        return Num + ":" + Name;    }}

 

  Automatic attributesPrivate variables are automatically generated, and no declarations need to be displayed.Object Initial Value Setting itemAssign values to accessible attributes and fields, and the constructor is not required. Er, isn't it refreshing.

  Sweet death you 3-Anonymous Method: We must declare the method before using it in the delegate. C #2.0 introduces the anonymous method, you can use delegate {// dosomething} to write the method code in an "inline" manner, directly associating the Code with the delegated instance, this makes the task of delegation instantiation more intuitive and convenient.

Sometimes we need to temporarily Save the intermediate results of some operations. We often declare a new type to save these intermediate results. On the surface, it seems that this is normal, and after careful consideration, we will find that this new type only serves this function and will not be used elsewhere, defining a new type for this function is indeed troublesome, such as the findstudent class.

  WithAnonymous Method, The findstudent class has no meaning ?), Because of the Relationship Between Automatic attributes, we can directly access the attributes and replace the predicates with the anonymous method.

Insert ad:

  Sweet death you 4-Set Initial Value: Apart from initializing objects like initializing arrays, we can also add set items for collections without repeating Add. Let's look at the new main function:

Static void main (string [] ARGs) {list <student> students = new list <student> () {New Student () {num = "001 ", name = "John"}, // use the object's Initial Value Setting item to initialize the object, instead of the constructor new student () {num = "002", name = "marry "}, new student () {num = "003", name = "John"}; // use the set initial value to initialize the set, you do not need to call the add method foreach (VAR student in students. findall (delegate (Student) {return student. name = "John";}) // use the anonymous method to complete the findstudent class function {console. writeline (student);} console. readkey ();}

Is it so pleasing to the eye. However, foreach's sentence is still a bit difficult. We had to make a big move.

  Your Terminator-Lamda expression:It is an upgraded version of the anonymous method, and its function is to simplify the writing of the anonymous method. Writing Method (parameter list) =>{ function body}

  Take the delegate (Student) {return student. Name = "John";} anonymous method as an example. Our parameter has only one student, and we use s instead of the form parameter.

The Lamda expression is S => S. Name = "John ".

By the way, use the foreach method of list <t>.

Another advertisement:

Sweet death your passers-by number-Anonymous type:The VaR keyword is used to declare the type without displaying the Declaration type. The specific type will be inferred by the compiler.

The final main function is:

Static void main (string [] ARGs) {list <student> students = new list <student> () {New Student () {num = "001 ", name = "John"}, // use the object's Initial Value Setting item to initialize the object, instead of the constructor new student () {num = "002", name = "marry "}, new student () {num = "003", name = "John"}; // use the set initial value to initialize the set. You do not need to call the add method var John = students repeatedly. findall (S => S. name = "John"); // uses VaR to declare the anonymous type. In fact, John is a list <student> John. foreach (j => console. writeline (j); // use the Lamda expression console. readkey ();}

This code looks quite comfortable.

Of course, there are still many syntactic sugar. As mentioned at the beginning of the article, the new features of C # are mostly syntactic sugar. Of course there are some other syntactic sugar, such as the ternary operator test? Expression1: expression2 has a syntactic sugar, writing

Expression1 ?? If expression2 is set to 1 and expression1 is null, execute expression2. Otherwise, execute expression1.

You are welcome to add more information.

-------------------------------------------- I am a split line ------------------------------------------------

Syntactic sugar can increase the readability of the program, but everything has two sides. For example, if you need to write some logic in the get method of the attribute, the automatic attribute is obviously not applicable. So you don't have to force it.

Don't eat your teeth...

 

 

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.