ASP.NET MVC---分部類的使用


       因為最近需要使用C#,所以特意花了幾天時間看了下C#的基本語法。其中,分部類型就引起了我的注意。

      分部類型是C#中一個很神奇的地方,它允許我們將一個類型的定義散布在各個文件中。像是下面這樣的例子:

//Example1.cs
public
partial class Example{ public string mName = "Example"; }
//Example2.cs
public partial class Example{ public void Show(){ Console.WriteLine(mName); } }

       然后我們通過一個測試類來測試:

public static void Main(string[] args){
    Example example = new Example();
example.Show();
}

      從這里我們可以看出,我們可以將數據放在一個分部類型中,然后將方法放在另一個同名的分部類型中。記得,必須是同名,否則它們之間的數據和方法並不認為是共享的。
      既然有這個東西,我們第一個念頭肯定是:有啥用啊?

      使用分部類型的第一個反應就是破壞了封裝性,原本類型就是封裝完成一個邏輯所需要的一系列數據和行為,但是使用分部類型,我們就可以將邏輯進行“分部”,就像上面一樣。但這並不是問題,上面的例子只是為了交代分部類的特性而已,實際上的分部類並不會這樣寫,更多時候,是將一個完整的解決方案中的多個邏輯功能散布在多個分部類型中。這樣的好處是顯而易見的,我們可以隨時修改或者替換這些功能,不需要跑到解決方案中特意找出相應位置的代碼。

       當然,分部類型的好處包括源碼控制,源碼拆分,這些都是比較抽象的話題,很難一下子明白,這里我也不班門弄斧,各位只要到MSDN上就能找到更多的資料。

      分部類型還有很多的限制。如果一個分部類型的訪問權限是public,那么我們就不能將其他分部類型的訪問權限設置為private,也就是說,它們的訪問權限必須是一樣的(畢竟它們之后是要合並為同一個類型)。由於C#是單根繼承的,所以,當一個分部類型繼承自一個基類的時候,其他分部類型也只能繼承自同一個基類。至於接口,就比較隨便了,而且,我們還可以在另一個分部類型中實現我們本該實現的接口方法。泛型類型中,所有的分部類型的約束都必須是一樣的。

     分部類型並不是一個難以理解的特性,但實際使用的時候卻很令新手費解,像是我下面的例子:

public partial class ShoppingCarts
    {
        StoreContext storeDb = new StoreContext();
        string ShoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";
        public static ShoppingCarts GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCarts();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }

        //Helper method to simplify shopping cart calls
        public static ShoppingCarts GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }

        public void AddToCart(Album album)
        {

            //Get the matching cart and album instances
            var cartItem = storeDb.Carts.SingleOrDefault(c => (c.CartId == ShoppingCartId) && (c.AlbumId == album.AlbumId));
            if (cartItem == null)
            {

                //Create a new cart item if no cart item exists
                cartItem = new Cart
                {
                    AlbumId = album.AlbumId,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                storeDb.Carts.Add(cartItem);
            }
            else
            {

                //If the item does exist in the cart,then add one to the quantity
                cartItem.Count++;
            }

            //Save changes
            storeDb.SaveChanges();
        }

        public int RemoveFromCart(int id)
        {

            //Get the Cart
            var cartItem = storeDb.Carts.Single(cart => (cart.CartId == ShoppingCartId) && (cart.RecordId == id));
            int itemCount = 0;
            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    storeDb.Carts.Remove(cartItem);
                }

                //Save changes
                storeDb.SaveChanges();
            }
            return itemCount;
        }

        public void EmptyCart()
        {
            var cartItems = storeDb.Carts.Where(cart => cart.CartId == ShoppingCartId);
            foreach (var cartItem in cartItems)
            {
                storeDb.Carts.Remove(cartItem);
            }

            //Save changes
            storeDb.SaveChanges();
        }

        public List<Cart> GetCartItems()
        {
            return storeDb.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
        }

        public int GetCount()
        {

            //Get the count of each item in the cart and sum them up
            int? count = (from cartItems in storeDb.Carts
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Count).Sum();

            //Return 0 if all entries are null
            return count ?? 0;
        }

        public decimal GetTotal()
        {

            //Multiply album price by count of that album to get
            //the current price for each of albums in the cart
            //sum all album price totals to get the cart total
            decimal? total = (from cartItems in storeDb.Carts
                              where cartItems.CartId == ShoppingCartId
                              select (int?)cartItems.Count * cartItems.Album.Price).Sum();
            return total ?? decimal.Zero;
        }

        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;
            var cartItems = GetCartItems();

            //Iterate over the items in the cart, adding the order details for each
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    AlbumId = item.AlbumId,
                    OrderId = order.OrderId,
                    UnitPrice = item.Album.Price,
                    Quantity = item.Count
                };

                //Set the order total of the shopping cart
                orderTotal += (item.Count * item.Album.Price);
                storeDb.OrderDetails.Add(orderDetail);
            }

            //Set the order's total to the orderTotal count
            order.Total = orderTotal;

            //Save the order
            storeDb.SaveChanges();

            //Empty the shopping cart
            EmptyCart();

            //Return the OrderId as the confirmation number
            return order.OrderId;
        }

        //We are using HttpContextBase to allow access to cookies
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {

                    //Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();

                    //Send tempCartId to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        //When a user has logged in, migrate their shopping cart to
        //be associated with their username
        public void MigrateCart(string userName)
        {
            var shoppingCart = storeDb.Carts.Where(c => c.CartId == ShoppingCartId);
            foreach (Cart item in shoppingCart)
            {
                item.CartId = userName;
            }
            storeDb.SaveChanges();
        }
    }

       還有一個不同名的分部類型:

 [Bind(Exclude = "OrderId")]
    public partial class Order
    {
        [ScaffoldColumn(false)]
        public int OrderId { get; set; }
        
        [ScaffoldColumn(false)]
        public string UserName { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        [StringLength(160)]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        [StringLength(160)]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Address is required")]
        [StringLength(70)]
        public string Address { get; set; }

        [Required(ErrorMessage = "City is required")]
        [StringLength(40)]
        public string City { get; set; }

        [Required(ErrorMessage = "State is required")]
        [StringLength(40)]
        public string State { get; set; }

        [Required(ErrorMessage = "PostalCode is required")]
        [DisplayName("PostalCode")]
        [StringLength(10)]
        public string PostalCode { get; set; }

        [Required(ErrorMessage = "Country is required")]
        [StringLength(40)]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone is required")]
        [StringLength(24)]
        public string Phone { get; set; }

        [Required(ErrorMessage = "Email is required")]
        [DisplayName("Email Address")]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+[A-Za-z]{2,4}", ErrorMessage = "Email is not valid")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [ScaffoldColumn(false)]
        public decimal Total { get; set; }

        [ScaffoldColumn(false)]
        public System.DateTime OrderDate { get; set; }

        public List<OrderDetail> OrderDetails { get; set; }

    }

      這是MVC經典的入門例程:MusicShopping。這里它定義了兩個分部類型,但是整個源碼就只有這兩個異名的分部類型,也就是說,它們是不能進行合並的。但為什么唯獨這兩個類型需要指定為分部類型呢?就算不指定,它們依然能夠發揮原有的作用。

      通過觀察它們各自的功能,我發現一個問題:它們都是需要隨時更改的模型項。其中Order的各項值是通過Submit提交的表單,而ShoppingCarts中有一個方法會對另一個模型項的值進行修改,然后顯示在頁面上。

      我不知道作者為什么需要指定它們為分部類型,他也並沒有特別交代。本人是剛學MVC也就兩天,很多東西弄不清楚,所以還請各位大神能夠指點迷津。
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM