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也就两天,很多东西弄不清楚,所以还请各位大神能够指点迷津。