ASP.NET MVC Framework Study Note - 1

Dictionary初始化:

Dictionary<string, int> myDict = new Dictionary<string, int> { 
            { "apple", 10 }, 
            { "orange", 20 }, 
            { "plum", 30 } 
        };

 

 Extension Methods(扩展方法)

1.定义一个扩展方法:

using System.Collections.Generic; 
 
public class ShoppingCart {
 
    public List<Product> Products { get; set; }
}


public
static class MyExtensionMethods { // 计算总价
public static decimal TotalPrices(this ShoppingCart cartParam) { decimal total = 0; foreach (Product prod in cartParam.Products) { total += prod.Price; } return total; } }


2. 应用扩展方法

using System; 
using System.Collections.Generic; 
 
class Program { 
 
    static void Main(string[] args) { 
        // create and populate ShoppingCart  
        ShoppingCart cart = new ShoppingCart { 
            Products = new List<Product> { 
                new Product {Name = "Kayak", Price = 275M}, 
                new Product {Name = "Lifejacket", Price = 48.95M}, 
                new Product {Name = "Soccer ball", Price = 19.50M}, 
                new Product {Name = "Corner flag", Price = 34.95M} 
            } 
        }; 
 
        // get the total value of the products in the cart 
        decimal cartTotal = cart.TotalPrices(); 
 
        Console.WriteLine("Total: {0:c}", cartTotal); 
         
    } 
}

ASP.NET MVC Framework Study Note - 1,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。