【问题标题】:access and set variables in a class from another class从另一个类访问和设置一个类中的变量
【发布时间】:2012-10-22 21:07:51
【问题描述】:

我有一个 shopping_cart.aspx.cs 文件,还有一个类文件 spcart.cs,

shopping_cart.aspx.cs

public partial class Ui_ShoppingCart : System.Web.UI.Page
{
    public int tax = 0;   
    public int subtotal = 0;
    public int granttotal = 0;  

    protected void Page_Load(object sender, EventArgs e)
         {
             -------------------------/////some code
         }
   --------------------------------/////some code
}

spcart.cs

public class Spcart
    {     
        public void updatecart(int pid,int qty)
         {
             ---------/////some code
         }
    }

现在我想在 Spcart 类的 class Ui_ShoppingCart 变量 tax、subtoal 和 granttotals 中设置一些值,所以我尝试过-->

Ui_ShoppingCart.tax

但它没有工作.........
有没有其他方法可以设置这些变量???
谁能帮我解决这个问题???

【问题讨论】:

  • 创建要使用其属性的类的实例。
  • 页面实例已经存在,不必创建。哪个对象拥有 Spcart 的实例?

标签: c# asp.net class variables partial-classes


【解决方案1】:

我觉得应该反过来

protected void Page_Load(object sender, EventArgs e)
{
   SpCart cart = new SpCart();
   cart.updateCart(124, 4);

   tax = cart.getComputedTax();
   subTotal = cart.getSubTotal();
   ...
}

想法是这些变量应该独立于您的 SpCart 代码。

public class Spcart
{     
     public void updatecart(int pid,int qty)
     {
         ---------/////some code
     }

     public int getComputedTax()
     {
       //can compute tax here
       int tax = whatever;
       return tax;
     }
}

计算逻辑仍然可以分成其他一些类

【讨论】:

    【解决方案2】:

    我认为您正在尝试从“Spcart”类访问“Ui_ShoppingCart”中声明的“税”属性。这是不可能的。相反,您必须将它们作为附加参数传递给 updatecart 方法。

    Spcart cart = new Spcart();
    cart.updatecart(pid,qty,tax);
    

    或者如果在“spcart”类的其他方法中使用了tax,则在构造函数中对其进行初始化。

    public class Spcart
    {     
     private int _tax = 0;
     public Spcart(int tax)
     {
       _tax = tax;
     }
     public void updatecart(int pid,int qty)
     {
        int amount = qty + _tax;
     }
    }
    

    并调用使用

    Spcart cart = new Spcart(tax);
    cart.updatecart(pid,qty);
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      相关资源
      最近更新 更多