ASP. net mvc Extension Method and chain Programming

Source: Internet
Author: User

ASP. net mvc Extension Method and chain Programming

Preface

There is no other purpose, that is, to introduce several points in ASP. NETMVC uses the C # Language Features and has some other trivial knowledge points. If you forcibly divide a range, it can only be said that it is related to MVC, some are peripheral knowledge, and some are included in the Framework. What is the name of MVC before? The content with gimmicks also has real ingredients. Therefore, to do well, you must first sharpen your skills. What is it? Well, although there is a lot of knowledge involved in the MVC framework that I can't finish with one article or two, what I can do is share it with you as much as I know, of course, this series will be improved over time.

 

1. Extension Method

The extension method is the knowledge in the C #3.0 feature. It is used most often in Linq and adds many query functions to IEnumerable and IEnumerable <T> types, I will not talk about it too much here, or I will talk about it.

Use Cases: There is a shopping list (Shopping Cart) object, which includes the function of adding or deleting items in the list.

Commodity object, which contains two attributes: Commodity Name and commodity price

Code 1-1

1 namespace BlogCase 2 public class Commodity 3 {4 public string Name {get; set;} 5 public float Price {get; set ;} 6} 7 8 namespace BlogCase 9 // <summary> 10 // shopping List 11 /// </summary> 12 public class ShoppingList13 {14 private List <Commodity> _ Commodities; 15 16 public List <Commodity> Commodities17 {18 get {return _ Commodities;} 19} 20 21 public ShoppingList () 22 {23 _ Commodities = new List <Commodity> (); 24} 25 26 public bool AddCommodity (Commodity commodity) 27 {28 _ Commodities. add (commodity); 29 return true; 30} 31 32 public bool RemoveCommodity (Commodity commodity) 33 {34 if (_ Commodities. contains (commodity) 35 {36 _ Commodities. remove (commodity); 37 return true; 38} 39 else40 {41 return false; 42} 43} 44}

Then, in this disturbing, fearful, expecting, and excited new demand, the list is required to provide a total price for all the items in the list without damaging the object structure.
Yes. This is a very reasonable demand, and now cursing does not help, because demand is always unknown. In an anxious and helpless moment, the dawn came, and it was the feature Extension Method in C #3.0.

See Code 1-2

Code 1-2

 1 using BlogCase; 2 using System.Linq; 3  4 namespace BlogCase.Extension 5 { 6     public static class ShoppingListExtension 7     { 8         public static float Total(this ShoppingList shoppintlist) 9         {10             return shoppintlist.Commodities.Sum(commodity => commodity.Price);11         }12     }13 }

The ShoppingListExtension type is a static class, which defines a static method Total. The method signature is a parameter of ShoppingList type, the only difference is that the this keyword is added before the ShoppingList type, and the extension method of the ShoppingList type has been defined. Let's take a look at the example code 1-3.

Code 1-3

 1 using BlogCase.Extension; 2  3 namespace BlogCase 4 {  5     class Program 6     { 7         static void Main(string[] args) 8         { 9             ShoppingList shoppinglistTest = new ShoppingList();10             shoppinglistTest.AddCommodity(new Commodity() { Name = "A", Price = 14.3f });11             shoppinglistTest.AddCommodity(new Commodity() { Name = "B", Price = 15 });12             shoppinglistTest.AddCommodity(new Commodity() { Name = "C", Price = 27.9f });13             shoppinglistTest.AddCommodity(new Commodity() { Name = "D", Price = 34.3f });14             Console.WriteLine(shoppinglistTest.Total().ToString());15             Console.ReadLine();16         }17     }18 }

Note that you need to reference the namespace of ShoppingListExtension of the extension method class. In the VS development environment, the extension method icons are different from those of common methods. 1

Figure 1

Run the code 1-3 and result 2.

Figure 2


2. chained Programming

The above content is to extend the type and add an extension method, so the coupling between objects is still relatively large. If the internal structure of ShoppingList is modified, shoppingListExtension also needs to be modified accordingly. Here we will mention why abstract programming is required, which will be mentioned later.
Now we need to change the dependency type in ShoppingListExtension to a higher level type, and then add an extension method to filter some data. From this, we can see a chained programming model. It is a good way to learn about linq and other knowledge.

Take a look at the sample code 2-1. This is the modified ShoppingList type.

Code 2-1

 1 namespace BlogCase 2 { 3     public class ShoppingList : IEnumerable<Commodity>, IEnumerator<Commodity> 4     { 5         private List<Commodity> _Commodities = new List<Commodity>(); 6         public void Add(Commodity commodity) 7         { 8             _Commodities.Add(commodity); 9         }10         public IEnumerator<Commodity> GetEnumerator()11         {12             return this;13         }14         IEnumerator IEnumerable.GetEnumerator()15         {16             return this;17         }18         private int _index = -1;19         public Commodity Current20         {21             get22             {23                 return _Commodities[_index];24             }25         }26         public void Dispose()27         {28 29         }30         object System.Collections.IEnumerator.Current31         {32             get33             {34                 return Current;35             }36         }37         public bool MoveNext()38         {39             if (_index < _Commodities.Count)40             {41                 _index++;42             }43             return (!(_index == _Commodities.Count));44         }45         public void Reset()46         {47             _index = -1;48         }49     }50 }

The ShoppingList type is redefined so that it can implement the IEnumerable <Commodity> interface type and IEnumerator <Commodity> interface type. Why do we need to implement the IEnumerable <Commodity> interface type? In the sample code, the extension methods of Linq are also used. These extension methods are based on the IEnumerable <T> type Extension and have been used in the first part. Careful friends may have noticed this.

The ShoppingListExtension type is also slightly modified. A new extension method is added and the previous extension method is modified to achieve the goal of decoupling.

Code 2-2

 1 using BlogCase; 2 using System.Linq; 3 namespace BlogCase.Extension 4 { 5     public static class ShoppingListExtension 6     { 7         public static float Total(this IEnumerable<Commodity> shoppintlist) 8         { 9             return shoppintlist.Sum(commodity => commodity.Price);10         }11 12         public static IEnumerable<Commodity> Filter(this IEnumerable<Commodity> shoppinglist, Func<Commodity, bool> commodityFilter)13         {14             var commodities = shoppinglist.Where(commodityFilter);15             return commodities;16         }17     }18 }

In the modified ShoppingListExtension class, the type of the Total extension method is changed, and the return type is defined as IEnumerable <Commodity> type in the Filter extension method, A parameter is defined. The delegate of the parameter type is Func <Commodity, bool>, which can be replaced by lambda expressions. It will be mentioned later in the article about lambda knowledge. After all the modifications are made, let's take a look at the code during the test.

Code 2-3

 1 using BlogCase.Extension; 2 namespace BlogCase 3 { 4     class Program 5     { 6         static void Main(string[] args) 7         { 8             ShoppingList shoppinglistTest = new ShoppingList(); 9             shoppinglistTest.Add(new Commodity() { Name = "A", Price = 50.3f });10             shoppinglistTest.Add(new Commodity() { Name = "B", Price = 60 });11             shoppinglistTest.Add(new Commodity() { Name = "C", Price = 70.9f });12             shoppinglistTest.Add(new Commodity() { Name = "D", Price = 80.3f });13 14             Console.WriteLine(shoppinglistTest.Filter(commodity=>commodity.Price>58).Total().ToString());15             Console.ReadLine();16         }17      }18 }

Running result 3

Figure 3

When the extension method Filter is called from the shoppinglistTest variable, a query condition (goods plus more than 58) is passed. The extension method returns the IEnumerable <Commodity> type mentioned above, then, call the IEnumerable <Commodity> type Extension Method Total.

Here, a simple chained programming model is coming out. If you are interested, you can go on to learn more about linq. Of course, it is important to read my subsequent articles before that.

 

 

 

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.

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.