简体   繁体   中英

Unable to reuse an Object of class

I am trying to create a page using object oriented design in C#. I wanted to use same instance object all the time in my page but it is not working .

Below is my code :

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlDataSource1.Delete();
        }
    }

    protected void ViewBalance_Click(object sender, EventArgs e)
    {
        string tempString = Request.Form["BalanaceField"];
        double bal;
        Double.TryParse(tempString, out bal);
        Session["CurrentBalance"] = bal;

        BankAccount newAcc = new BankAccount(bal);

        resultDiv.InnerHtml = "<h1> Current Balance is $" + 
            newAcc.getCurrentBalance() + "</h1>";

        transactionDiv.Style["display"] = "block";
        newAccountDiv.Style["display"] = "none";
    }

    protected void Withdraw_Click(object sender, EventArgs e)
    {
        string currentBal = Session["CurrentBalance"].ToString();
        double bal;
        Double.TryParse(currentBal, out bal);
        BankAccount newAcc = new BankAccount(bal);

        double withdrwaAmount;

        Double.TryParse(Request.Form["WithdrawField"], out withdrwaAmount);

        if (newAcc.validWithDraw(withdrwaAmount))
        {
            newAcc.withDraw(withdrwaAmount);
            Session["CurrentBalance"] = newAcc.getCurrentBalance();
            insertRecord("Withdaw", withdrwaAmount, newAcc.getCurrentBalance());

            resultDiv.InnerHtml = 
                "<h1>Amount Withdrwan Succesfully. Current Balance is $ " +
                newAcc.getCurrentBalance() + "</h1>";
        }
        else
        {
            resultDiv.InnerHtml = 
                "<h1>You cann't ovewdraw you  account. Your current Balance is $" + 
                bal + " and you are trying to widthdraw $" + 
                withdrwaAmount + " </h1>";
        }
    }

    protected void Deposit_Click(object sender, EventArgs e)
    {
        string currentBal = Session["CurrentBalance"].ToString();
        double bal;
        Double.TryParse(currentBal, out bal);
        BankAccount newAcc = new BankAccount(bal);

        double depositAmount;

        Double.TryParse(Request.Form["DeopositField"], out depositAmount);

        double newBalance = newAcc.deposit(depositAmount);

        Session["CurrentBalance"] = newBalance;

        insertRecord("Deposit", depositAmount, newAcc.getCurrentBalance());

        resultDiv.InnerHtml = 
            "<h1>Amount Deposit  Succesfully. Current Balance is $ " +
            newAcc.getCurrentBalance() + "</h1>";
    }

    protected void InterestCount_Click(object sender, EventArgs e)
    {
        string currentBal = Session["CurrentBalance"].ToString();
        double bal;
        Double.TryParse(currentBal, out bal);
        BankAccount newAcc = new BankAccount(bal);

        double interestMonths;

        Double.TryParse(Request.Form["MonthsField"], out interestMonths);

        double interest = bal * (0.10) * (interestMonths / 12);

        resultDiv.InnerHtml = 
            "<h1>Total amount with acculmated Interest would be $ " +
            (newAcc.getCurrentBalance() + interest) + 
            " and Interest would be $:" + interest + "</h1>";
    }

    public void insertRecord(string type, double amount, double finalAMount)
    {
        DataView dv = 
            (DataView) SqlDataSource1.Select(DataSourceSelectArguments.Empty);

        int id = dv.Count + 1;

        SqlDataSource1.InsertParameters.Add("Id", id.ToString());
        SqlDataSource1.InsertParameters.Add("Type", type);
        SqlDataSource1.InsertParameters.Add("Amount", amount.ToString());
        SqlDataSource1.InsertParameters.Add("Balance", finalAMount.ToString());
        SqlDataSource1.Insert();
    }
}

As we can see I have to always create new instance of BankAccount class in each method.

Ideally I would like just one object for entire page and reuse it when needed.

Reading your code it won't make any difference in performance. Your page is created (an object of class _Default is instantiated) with every request.

There are some possibilities:

  1. Declare the field private or protected above your methods, at class level. But as you use this object only in Click methods you will have one BankAccount object per request, which you already have. (will not increase performance, nor reduce memory usage)
  2. You can declare the field static, but you will have the same object for all the users on your website (you don't want someone to see a wrong balance if two requests are performed at the same time).
  3. You can store the bank account object on session and use it, if you don't want to create it every time. (will increase memory usage, you will also use performance, as the object is serialized, deserialized and a cast must be performed)

Why do you want to do this ? Performance will not be better and the memory usage will not be optimized.

Place your definition for BankAccount newAcc just above protected void Page_Load(object sender, EventArgs e) (do some research on "scope" to understand why this works)

Inside Page_Load create your first instance

newAcc = new BankAccount(); //note that you'll want a constructor that doesn't have a balance argument

Make sure you have a public way of modifying the balance field, then when you need to change the balance:

newAcc.balance = whatever; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM