C # The Extension Method encapsulates if/else, swith/case, and while

Source: Internet
Author: User

This article discusses how to encapsulate if/else, swith/case, and while using extension methods. By using these extensions, the code written will use very few braces {}. Please judge how the extension works!
Declaration: This article is an article about (change) and changing (form) states. It only proposes an idea. The provided code is just an example. It can be tested but not perfect.

First, let's look at if/else and swith/case, both of which are used to express the branch structure in the code. Here we encapsulate them into an If extension:

Public static T If <T> (this T t, Predicate <T> predicate, Action <T> action) where T: class
{
If (t = null) throw new ArgumentNullException ();
If (predicate (t) action (t );
Return t;
}

Take a look at the following call code to generate a People instance, so that he can have a good rest and then work:

Public static void Test1 ()
{
// General Code
People people1 = new People {Name = "ldp615", IsHungry = true, IsThirsty = true, IsTired = true };
If (people1.IsHungry) people1.Eat ();
If (people1.IsThirsty) people1.Drink ();
If (people1.IsTired) people1.Rest ();
Lele1.work ();
// Use the Extension Method
People people2 = new People {Name = "ldp615", IsHungry = true, IsThirsty = true, IsTired = true}
. If (p => p. IsHungry, p => p. Eat ())
. If (p => p. IsThirsty, p => p. Drink ())
. If (p => p. IsTired, p => p. Rest ());
Lele2.work ();
}

In the extension method, If can be chained by clicking ".". For more information, see my essay "c # chained programming".
General Code and use Expansion

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.