自学》2.网页弹窗计算商品价格

/// <summary>
/// Goods 是商品类
/// </summary>
public class Goods
{
    public Goods()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public Goods(string name, decimal priceDecimal)
    {
        this.PriceDecimal = priceDecimal;
        this.Name = name;
    }
    public Goods(string name, decimal priceDecimal,string htmlUrl)
    {
        this.PriceDecimal = priceDecimal;
        this.Name = name;
        HtmlUrl = htmlUrl;
    }
    public decimal PriceDecimal { get; set; }
    public string Name { get; set; }
    public string HtmlUrl { get; set; }
}

先写个商品类,有商品名,价格,网页链接地址(这个例子没用)。

using System.Collections.Generic;
using System.Text;
/// <summary>
/// 订单
/// </summary>
public class Indent:List<Goods>
{
    public Indent()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 订单的数目
    /// </summary>
    public int Number
    {
        get { return Count; }
    }

    /// <summary>
    /// 订单金额
    /// </summary>
    public decimal GetMoneyDecimal( )
    {
        decimal money = 0;
        foreach (Goods goods in this)
        {
            money += goods.PriceDecimal;
        }
     return money;
    }
    /// <summary>
    /// 打印订单
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        StringBuilder sb=new StringBuilder();
        sb.Append("订单详情 ");
        foreach (Goods goods in this)
        {
            sb.Append(goods.Name).Append(" 单价:").Append(goods.PriceDecimal).Append(", ");
        }
        sb.Append("合计:").Append(this.GetMoneyDecimal());
        return sb.ToString();
    }
}

然后是一个订单类,订单由商品组成,用了List<Goods>。

   protected void Button1_Click(object sender, EventArgs e)
    {
        Indent myIndent=new Indent();
        Goods goods1=new Goods("镰刀",2.8m);
       Goods goods2=new Goods("斧头",5.2m);
        myIndent.Add(goods2);
        myIndent.Add(goods1);
       string str= myIndent.ToString();
        Response.Write("<script>alert('" + str + "')</script>");
       }

最后一个按钮测试下,就好了,哈哈^_^

注意:做这个折腾了我半个多小时,就是因为最后一个alert,中间的字符串是不能有换行符的,我先前用的是StringBuilder.AppendLine();这个方法,导致字符串有换行,一直不能alert出来。

只有让自己变得优秀,才有资格对这个世界指手画脚。
原文地址:https://www.cnblogs.com/alasq/p/4876029.html