问题
i'v a shopping_cart.aspx.cs file & also have a class file 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
}
}
now i want to set some values in class Ui_ShoppingCart
variables tax, subtoal & granttotals from class Spcart, so i'd tried-->
Ui_ShoppingCart.tax
but it didnt worked.........
is there any other way to set these variables ???
can anyone help me about this???
回答1:
I think it should be the other way round
protected void Page_Load(object sender, EventArgs e)
{
SpCart cart = new SpCart();
cart.updateCart(124, 4);
tax = cart.getComputedTax();
subTotal = cart.getSubTotal();
...
}
The idea is those variables should independent of your SpCart code.
public class Spcart
{
public void updatecart(int pid,int qty)
{
---------/////some code
}
public int getComputedTax()
{
//can compute tax here
int tax = whatever;
return tax;
}
}
The computation logics can still be separated into some other class
回答2:
I think you are trying to access "tax" property declared in "Ui_ShoppingCart" from "Spcart" class. It is not possible to do it. Instead you have to pass them as additional parameters to updatecart method.
Spcart cart = new Spcart();
cart.updatecart(pid,qty,tax);
Or if tax is used in other methods of the "spcart" class, initialize it in the contructor.
public class Spcart
{
private int _tax = 0;
public Spcart(int tax)
{
_tax = tax;
}
public void updatecart(int pid,int qty)
{
int amount = qty + _tax;
}
}
And call using
Spcart cart = new Spcart(tax);
cart.updatecart(pid,qty);
来源:https://stackoverflow.com/questions/13019896/access-and-set-variables-in-a-class-from-another-class