5.1.3 Using Extension Methods
parent
df3b9aacdf
commit
aa49052a81
|
@ -0,0 +1,18 @@
|
|||
namespace automatically_implemented_properties
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
private string name;
|
||||
|
||||
public int ProductID { get; set; }
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return ProductID + name; }
|
||||
set { name = value; }
|
||||
}
|
||||
public string Description { get; set; }
|
||||
public decimal Price { get; set; }
|
||||
public string Category { set; get; }
|
||||
}
|
||||
}
|
|
@ -1,5 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using automatically_implemented_properties;
|
||||
|
||||
namespace automatically_implemented_properties
|
||||
{
|
||||
|
@ -7,36 +9,35 @@ namespace automatically_implemented_properties
|
|||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
// create a new Product object and use method on it
|
||||
ProcessProduct(new Product
|
||||
// create and populate Shopping Cart
|
||||
ShoppingCart cart = new ShoppingCart
|
||||
{
|
||||
ProductID = 100,
|
||||
Name = "Kayak",
|
||||
Description = "A boat for one person",
|
||||
Price = 275M,
|
||||
Category = "Watersports"
|
||||
});
|
||||
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 total value of the products in cart
|
||||
decimal cartTotal = cart.TotalPrices();
|
||||
|
||||
Console.WriteLine("Total: {0:c}", cartTotal);
|
||||
}
|
||||
|
||||
private static void ProcessProduct(Product prodParam)
|
||||
{
|
||||
// ... statements to process product in some way
|
||||
}
|
||||
}
|
||||
|
||||
public class Product
|
||||
public static class MyExtensionMethod
|
||||
{
|
||||
private string name;
|
||||
|
||||
public int ProductID { get; set; }
|
||||
|
||||
public string Name
|
||||
public static decimal TotalPrices(this ShoppingCart cartParam)
|
||||
{
|
||||
get { return ProductID + name; }
|
||||
set { name = value; }
|
||||
decimal total = 0;
|
||||
foreach (Product prod in cartParam.Products)
|
||||
{
|
||||
total += prod.Price;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
public string Description { get; set; }
|
||||
public decimal Price { get; set; }
|
||||
public string Category { set; get; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace automatically_implemented_properties
|
||||
{
|
||||
public class ShoppingCart
|
||||
{
|
||||
public List<Product> Products { get; set; }
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue