5.1.3 Using Extension Methods

master
Jason Zhu 2021-07-05 18:21:52 +10:00
parent df3b9aacdf
commit aa49052a81
3 changed files with 51 additions and 23 deletions

View File

@ -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; }
}
}

View File

@ -1,5 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using automatically_implemented_properties;
namespace automatically_implemented_properties namespace automatically_implemented_properties
{ {
@ -7,36 +9,35 @@ namespace automatically_implemented_properties
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
// create a new Product object and use method on it // create and populate Shopping Cart
ProcessProduct(new Product ShoppingCart cart = new ShoppingCart
{ {
ProductID = 100, Products = new List<Product>
Name = "Kayak", {
Description = "A boat for one person", new Product {Name = "Kayak", Price = 275M},
Price = 275M, new Product {Name = "Lifejacket", Price = 48.95M},
Category = "Watersports" 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 static decimal TotalPrices(this ShoppingCart cartParam)
public int ProductID { get; set; }
public string Name
{ {
get { return ProductID + name; } decimal total = 0;
set { name = value; } 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; }
} }
} }

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace automatically_implemented_properties
{
public class ShoppingCart
{
public List<Product> Products { get; set; }
}
}